Exception creating JSON with LINQ

孤者浪人 提交于 2019-12-10 13:57:54

问题


I am trying to create JSON with the following code:

        JArray jInner = new JArray("document");
        JProperty jTitle = new JProperty("title", category);
        JProperty jDescription = new JProperty("description", "this is the description");
        JProperty jContent = new JProperty("content", content);
        jInner.Add(jTitle);
        jInner.Add(jDescription);
        jInner.Add(jContent);

when I get to the jInner.Add(jTitle), I get the following exception:

System.ArgumentException: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.
   at Newtonsoft.Json.Linq.JContainer.ValidateToken(JToken o, JToken existing)
   at Newtonsoft.Json.Linq.JContainer.InsertItem(Int32 index, JToken item, Boolean skipParentCheck)
   at Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index, Object content, Boolean skipParentCheck)

Can anybody help and tell me what am I doing wrong?


回答1:


It doesn't make sense to add a property to an array. An array consists of values, not key/value pairs.

If you want something like this:

[ {
  "title": "foo",
  "description": "bar"
} ]

then you just need an intermediate JObject:

JArray jInner = new JArray();
JObject container = new JObject();
JProperty jTitle = new JProperty("title", category);
JProperty jDescription = new JProperty("description", "this is the description");
JProperty jContent = new JProperty("content", content);
container.Add(jTitle);
container.Add(jDescription);
container.Add(jContent);
jInner.Add(container);

Note that I've removed the "document" argument from the JArray constructor call too. It's not clear why you had it, but I strongly suspect you don't want it. (It would have made the first element of the array the string "document", which would be fairly odd.)



来源:https://stackoverflow.com/questions/29168701/exception-creating-json-with-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!