使用Json.Net通过Linq查找节点以插入子节点或删除它

时间:2016-11-22 03:52:39

标签: c# json linq json.net

我对Json数据有这种格式:

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

如何使用' Guid'通过Linq查找特定节点?过滤字段?

如何在所选节点中添加子节点(' MenuEntries')并删除此节点?

1 个答案:

答案 0 :(得分: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);

然后,您可以在MenuEntries中选择节点:

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