我有一个如下所示的 json 数据,如果 Item_id 匹配,我想向“revs”数组添加新条目,假设我正在查看的 Item_id 是 1,现有的 json 数据由“revs”数组中的两个项目组成,并想添加新条目
{
"Root" : [
{
"Item_Name" : "Test",
"Items" : [
{
"Item_id" : "1",
"revs" : [
{
"rev_id" : "1"
},
{
"rev_id" : "3"
},
{
"rev_id" : "need to add new entry here"
}
]
},
{
"Item_id" : "2",
"revs" : [
{
"rev_id" : "1"
}
]
}
]
}
]
}
我这样解析json数据
JObject jsonObject = JObject.Parse(<the json data above>);
在 Item_id 匹配后迭代到“revs”数组,我创建一个分配给新条目数据的 JObject
JObject new_rev = new JObject();
new_rev["rev_id"] = "need to add new entry here"
我应该怎么做才能使我的 new_rev 数据反射(reflect)在 jsonObject 中?
p/s: 我之前使用 C++ 的 jsoncpp,我只是循环使用引用对象,我可以轻松地将 json 数据修改到其中
谢谢。
最佳答案
假设 Root
在数组中只有一项并且假设 Item_id
是唯一的
JObject jsonObject = JObject.Parse(<the json string>);
JObject new_rev = new JObject();
new_rev["rev_id"] = "need to add new entry here";
JArray items = jsonObject["Root"][0]["Items"].Value<JArray>();
foreach(var item in items){
if(item.Value<JObject>()["Item_id"].Value<string>() == "1"){
item["revs"].Value<JArray>().Add(new_rev);
break;
}
}
关于c# - json.net,将新对象/项目添加/附加到现有 JSON 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908830/