2016-08-12 79 views
1

我有一個JSON數據如下,我想添加新的條目「revs」數組如果Item_id匹配,讓我說Item_id我看着1,現有的JSON數據由兩個項目的「轉速」數組中,並希望添加新條目json.net,添加/ apped新的對象/項目到現有的JSON對象

{ 
    "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" 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

我喜歡這個

JObject jsonObject = JObject.Parse(<the json data above>); 

迭代JSON數據解析成「轉速」後陣Item_id匹配並且我創建了一個JObject,並被添加到新的條目數據

JObject new_rev = new JObject(); 
new_rev["rev_id"] = "need to add new entry here" 

我該怎麼做才能讓我的new_rev數據反映在jsonObject中?

P/S:ⅰ通過使用jsoncpp用於C++之前和我只是循環參照對象,我可以具有經修飾的JSON數據到它容易

感謝。

回答

2

假設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

+0

你的答案^ h查詢語法似乎工作,但我給JSON數據僅僅是例子,其實有多重根和多個項目,反正感謝您的幫助。 – hghew

1

我試着找出更好的方式來在數據添加,到底實現LINQ(方法語法)讓我的生活更輕鬆,下面的代碼爲我工作,eventhough包含多個Root,項目

對不起,我還是LINQ的新手,也許有人可以啓發我做同樣的

JObject jsonObject = JObject.Parse(<existing json data>); 
JObject newNode = new JObject(); 
newNode["rev_id"] = "need to add new entry here" 

jsonObject["Root"].Children() 
         .Where(w => w["Item_Name"].ToString() == selectedItemName) 
         .Select(s => s["Items"]).Children() 
         .Where(w => w["Item_id"].ToString() == selectedItemId) 
         .Select(s => s["revs"]).Children() 
         .LastOrDefault().AddAfterSelf(newNode);