使用LINQ创建JSON时出现异常

5
我将尝试使用以下代码创建 JSON:
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);

当我到达 jInner.Add(jTitle) 时,我会得到以下异常:

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)

有人可以帮忙告诉我我在做什么错了吗?


如果我的回答不符合您的要求,请提供您尝试生成的JSON示例。 - Jon Skeet
1个回答

11

将属性添加到数组中是没有意义的。数组由值组成,而不是键/值对。

如果你想要类似下面这样的东西:

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

那么你只需要一个中间的 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);
请注意,我已经从JArray构造函数调用中删除了"document"参数。不清楚您为什么要这样做,但我强烈怀疑您不需要它。(这会使数组的第一个元素成为字符串"document",这相当奇怪。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接