gpt4 book ai didi

c# - 使用 LINQ 创建 JSON 异常

转载 作者:太空狗 更新时间:2023-10-29 22:36:55 30 4
gpt4 key购买 nike

我正在尝试使用以下代码创建 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)

任何人都可以帮助并告诉我我做错了什么吗?

最佳答案

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

如果你想要这样的东西:

[ {
"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",这会很奇怪。)

关于c# - 使用 LINQ 创建 JSON 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29168701/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com