gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:36 26 4
gpt4 key购买 nike

我有这种格式的 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')并删除这个节点?

最佳答案

您可以创建一个模型:

    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
}
}

关于c# - 通过 Linq 使用 Json.Net 查找节点以插入或删除子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40733484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com