c# - json.net,将新对象/项目添加/附加到现有 JSON 对象中

标签 c# json json.net

我有一个如下所示的 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;
        }
    }

在这里查看 https://dotnetfiddle.net/IYVULd

关于c# - json.net,将新对象/项目添加/附加到现有 JSON 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908830/

相关文章:

c# - 使用 ImmutableList(仅 Release模式)在 UWP 上使用 JSON.NET 反序列化问题

c# - 不抛出异常(在 Win7 中?)

c# - CheckedListbox DisplayMember 和 ValueMember

javascript - Dailymotion api 使用 json 和 jquery 获取视频信息

javascript - 从 JSON 获取的 Google map API 上的绑定(bind)标记

json:无法将对象解码为 Auction.Item 类型的 Go 值

c# - 当字符串比较断言看起来应该通过时却失败

.net - Json.Net:使用 SelectToken 在不知道元素名称的情况下获取值?

c# - json.net 错误 : unexpected token deserializing object

c# - 是否可以将对象的方法发送给函数?