【问题标题】:building a dynamic request with child attributes使用子属性构建动态请求
【发布时间】:2014-01-14 21:56:15
【问题描述】:

我需要创建一个带有子属性的动态请求,但我不完全确定该怎么做。我已经安装了 newtonsoft.json,所以我正在考虑制作一系列类,然后将它们序列化,但我还必须传入凭据/消费者密钥 Oauth 的东西。

{
  "type": "email",
  "subject": "Creating a case via the API",
  "priority": 4,
  "status": "open",
  "labels": [
    "Spam",
    "Ignore"
  ],
"message": {
    "direction": "in",
    "status": "received",
    "to": "someone@desk.com",
    "from": "someone-else@desk.com",
  }

因此,为了有上面的请求,我是否会创建一个主类,它具有类型/主题/状态等属性,然后它也会包含我的其他类消息。我只是想弄清楚序列化如何转换类

【问题讨论】:

  • “可能做一系列的类,然后序列化”你不能完成哪一部分?
  • 好吧,我只是想知道这是否是最好的主意。我会更新我的问题
  • 您需要定义动态的含义。
  • 动态因为在某些字段中不需要,或者像标签一样它可能有两个以上的标签

标签: c# json formatting json.net


【解决方案1】:

希望对你有帮助

public class dataObj
{
   public string type { get; set; }
   public string subject { get; set; }
   public int priority { get; set; }
   public string status { get; set; }
   public IList<string> labels { get; set; }
   public IDictionary<string, string> message { get; set; }
}



private void testbutton_Click(object sender, EventArgs e)
    {
        try {
            string json = @"{
                ""type"": ""email"",
                ""subject"": ""Creating a case via the API"",
                ""priority"": 4,
                ""status"": ""open"",
                ""labels"": [
                ""Spam"",
                ""Ignore""
                ],
            ""message"": {
            ""direction"": ""in"",
            ""status"": ""received"",
            ""to"": ""someone@desk.com"",
            ""from"": ""someone-else@desk.com""
            }
          }";
            dataObj data = Newtonsoft.Json.JsonConvert.DeserializeObject<dataObj>(json);

        }
        catch { 

        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多