Kla*_*aus 5 c# linq json json.net
我正在尝试使用以下代码创建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);
Run Code Online (Sandbox Code Playgroud)
当我到达时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)
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮忙告诉我,我做错了什么?
向数组添加属性没有意义.数组由值组成,而不是键/值对.
如果你想要这样的东西:
[ {
"title": "foo",
"description": "bar"
} ]
Run Code Online (Sandbox Code Playgroud)
那么你只需要一个中级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);
Run Code Online (Sandbox Code Playgroud)
请注意,我也"document"从JArray构造函数调用中删除了参数.目前尚不清楚为什么会这样,但我强烈怀疑你不想要它.(它会使数组的第一个元素成为字符串"document",这将是相当奇怪的.)
| 归档时间: |
|
| 查看次数: |
7101 次 |
| 最近记录: |