转换为格式正确的JSON

时间:2016-01-21 09:15:51

标签: json serialization json.net

我的任务是调用一个API,需要将JSON有效负载作为其请求.JSON的示例格式如下:

{  
   "method":"methodname",
   "in":[  
      {  
         "account":"acme",
         "context":"abc123"
      },
      "content",
      {  
         "mSearchText":"chocolate",
         "mItemDataIDs":[  
            "Entry:ID",
            "Entry:EntryRef",
            "Entry:CategoryID"
         ]
      }
   ]
}

我正在使用JSON.NET(Newstonsoft)从.net对象构造我的JSON。 我面临的问题是正确构建“在”部分.. 它似乎是一个对象数组,但只有第二个项目有标题(“content”,{.....} )..

我能得到的最接近的是:

{
  "method": "methodname",
  "in":[
    {
      "account": "PANDO",
      "context": "sdfsd22342"
    },
    {
      "mSearchText":"chocolate",
      "mItemDataIDs":[
        "Entry:ID",
        "Entry:EntryRef",
        "Entry:CategoryID"
      ]
    }
  ]
}

除了“content”之外,其他内容相同,缺失:

到目前为止我的代码是:

public class Payload
    {
        public string method { get; set; }
        [JsonProperty("in")]
        public List<object> Items { get; set; }
    }

    public class AccountDetails
    {
        public string account { get; set; }
        public string context { get; set; }
    }

    [JsonObject(Title = "content")]
    public class Content
    {
        public string mSearchText { get; set; }
        public string[] mItemDataIDs { get; set; }
    }

        Payload payload = new Payload();
        payload.method = "methodname";
        payload.Items = new List<object>();
        payload.Items.Add(new AccountDetails
        {
            account = "acme",
            context = "abc123"
        });
        Content conent = new Content
        {
            mSearchText = "chocolate",
            mItemDataIDs = new string[] { "Entry:ID", "Entry:EntryRef", "Entry:CategoryID" }
        };
        payload.Items.Add(conent);

        string jsonObject = JsonConvert.SerializeObject(payload, Formatting.Indented);

关于我能做什么的任何建议?

0 个答案:

没有答案