gpt4 book ai didi

c# - 无法使用 C# (NewtonSoft) 编辑 JSON,因为出现错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:35 25 4
gpt4 key购买 nike

我正在尝试从 JSON 文件更改 JSON,以便我可以运行它以获得 JSON 响应,我在这篇文章中找到了代码:Change values in JSON file (writing files)谁能解决这个问题?

错误:

An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll

Additional information: Set JArray values with invalid key value: "filter". Int32 array index expected.

JSON:

[{
"tablename" : "table",
"columns" : "id, name",
"filter" : "id = 10"
}]

代码:

string json = File.ReadAllText("file.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["filter"] = "id = 20";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("file.json", output);

(JSON 用于与网络服务对话)

最佳答案

我认为这应该是:

jsonObj[0]["filter"] = "id = 20";

因为您的 JSON 是一个数组。所以 0 是数组中的第一个对象。

关于c# - 无法使用 C# (NewtonSoft) 编辑 JSON,因为出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135312/

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