2016-11-22 46 views
2

一個節點我有這種格式的JSON數據:發現通過LINQ的使用Json.Net插入一個子節點或刪除其

{ 
    "Name": "MainMenu", 
    "Text": "", 
    "Guid": "047bf56e75f44c14b56a4b84f3af6dbe", 
    "ParentGuid": "00000000000000000000000000000000" 
    "MenuEntries": [{ 
      "Name": "Home", 
      "Text": "Home", 
      "Guid": "1e3df5fb3d8e463b8f37e8ccdb291802", 
      "ParentGuid": "047bf56e75f44c14b56a4b84f3af6dbe", 
      "MenuEntries": [{ 
        "Name": "About", 
        "Text": "About", 
        "Guid": "f476a3444e2943668d86433f4c88374c", 
        "ParentGuid": "1e3df5fb3d8e463b8f37e8ccdb291802", 
        "MenuEntries": [] 
       }, { 
        "Name": "Contact", 
        "Text": "Contact Us", 
        "Guid": "51b461ec6abd4aecb95cf662e8e15ae6", 
        "ParentGuid": "1e3df5fb3d8e463b8f37e8ccdb291802", 
        "MenuEntries": [] 
       } 
      ] 
     }, { 
      "Name": "About", 
      "Text": "About", 
      "Guid": "6954d6f747ef4d2dae33de0f0efae9cc", 
      "ParentGuid": "047bf56e75f44c14b56a4b84f3af6dbe", 
      "MenuEntries": [] 
     }, { 
      "Name": "Contact", 
      "Text": "Contact Us", 
      "Guid": "634cfb99b70b4395b94061ae4f082aba", 
      "ParentGuid": "047bf56e75f44c14b56a4b84f3af6dbe", 
      "MenuEntries": [] 
     } 
    ] 
} 

如何找到通過LINQ的使用「的Guid一個特定節點'用於過濾的字段?

如何在所選節點中添加子節點('MenuEntries')並刪除此節點?

+0

遠?你使用Json.Net –

+0

我解析了字符串JObject,並試圖使用'Where'擴展名,但無法弄清楚如何使用它。 – eSPiYa

回答

1

您可以創建一個模型:

public class MenuEntry 
    { 
     public string Name { get; set; } 
     public string Text { get; set; } 
     public string Guid { get; set; } 
     public string ParentGuid { get; set; } 
     public List<object> MenuEntries { get; set; } 
    } 

    public class RootObject 
    { 
     public string Name { get; set; } 
     public string Text { get; set; } 
     public string Guid { get; set; } 
     public string ParentGuid { get; set; } 
     public List<MenuEntry> MenuEntries { get; set; } 
    } 

和反序列化:

string jsonString = System.IO.File.ReadAllText(Server.MapPath("~/json/test.json")); 
RootObject Menu = JsonConvert.DeserializeObject<RootObject>(jsonString); 

然後你可以選擇像在的菜單項節點:什麼都ü試過這麼

foreach (var item in Menu.MenuEntries) 
    { 
     if (item.Guid == "1e3df5fb3d8e463b8f37e8ccdb291802") 
      { 
       Console.WriteLine(item.Name); 
       //=> Home 
      } 
    } 
+0

我試過這個路徑,但由於某些原因,搜索到的節點沒有作爲參考返回,而是作爲該節點的新副本。 – eSPiYa

+0

我剛更新了我的答案以訪問節點。 – Yanga

+0

這可能適用於RootObject的子項。我已經試過做某種遞歸函數來檢查子項的MenuEntries,但是提取的節點不會作爲引用返回,而是返回新的副本。 – eSPiYa