我正在尝试编辑JSON文件以附加值。但是,我找不到找到预期结果的方法。鉴于以下JSON:
{
"First": "1",
"Second": "2",
"A_lot": [
{
"Address":"Str"
},
{
"Fruits" : [ "apple", "orange" ],
"colors": : []
}
],
"last": "end
}
我想添加一种叫做香蕉的水果和我的JSON
{
"First": "1",
"Second": "2",
"A_lot": [
{
"Address":"Str"
},
{
"Fruits" : [ "apple", "orange", "banana" ],
"colors:" : []
}
],
"last": "end
}
我在网上搜索,但找不到任何相关信息。 当我尝试运行此命令时:
var myjson = File.ReadAllText(pathtojson);
JObject newDeploymentProfileDocument = JObject.Parse(myjson);
var deploymentProperties = newDeploymentProfileDocument["A_lot"][1];
var myFruit = "banana";
deploymentProperties["Fruits"].AddAfterSelf(myFruit);
File.WriteAllText(myjson, newDeploymentProfileDocument.ToString());
我遇到以下错误:
Newtonsoft.Json.JsonException:'Newtonsoft.Json.Linq.JProperty不能有多个值。
由于我是C#的新手,更不用说C#和json文件了,您能指出我所缺少的内容吗?预先感谢
答案 0 :(得分:0)
您发送的JSON似乎不是正确的格式。如果您的意思是这样的话:
{
"First": "1",
"Second": "2",
"A_lot": [
{
"Address": "Str",
"Fruits": [ "apple", "orange" ],
"colors": []
}
],
"last": "end"
}
就像其他人在评论中提到的那样,只需这样做:
...
var deploymentProperties = (JArray)newDeploymentProfileDocument["A_lot"][0]["Fruits"];
var myFruit = "banana";
deploymentProperties.Add(myFruit);
...
已编辑
如果您不想更改JSON结构,则可以使用以下方法:
var deploymentProperties = (JArray)newDeploymentProfileDocument["A_lot"][1]["Fruits"];
var myFruit = "banana";
deploymentProperties.Add(myFruit);