如何在JSON对象中选择所有子对象?例如,我们有一个JSON对象,该对象包含公司的所有组织单位,我们希望选择以字母A开头的所有组织单位。
我找不到任何解决方案,这些解决方案像在XPath的SelectNodes
方法中一样递归选择所有子对象。
{
"orgname": "Org A",
"subOrgs": [
{
"orgname": "Org B",
"subOrgs": [
{
"orgname": "Org A",
"subOrgs": [
{
"orgname": "Org B",
"subOrgs": []
},
{
"orgname": "Org C1",
"subOrgs": []
}
]
},
{
"orgname": "Org A1",
"subOrgs": [
{
"orgname": "Org B2",
"subOrgs": []
},
{
"orgname": "Org C1",
"subOrgs": []
}
]
}
]
},
{
"orgname": "Org C",
"subOrgs": [
{
"orgname": "Org A4",
"subOrgs": [
{
"orgname": "Org B2",
"subOrgs": []
},
{
"orgname": "Org C3",
"subOrgs": []
}
]
},
{
"orgname": "Org A5",
"subOrgs": [
{
"orgname": "Org B4",
"subOrgs": []
},
{
"orgname": "Org C2",
"subOrgs": []
}
]
}
]
}
]
}
您可以使用这样的linq-to-json查询:
var orgs = JObject.Parse(json);
var orgsStartingWithA =
orgs.DescendantsAndSelf()
.OfType<JObject>()
.Where(t => t["orgname"] != null && t["orgname"].Value<string>().StartsWith("Org A"))
.ToList();
foreach (var org in orgsStartingWithA)
{
Console.WriteLine(org["orgname"]);
}
小提琴:https://dotnetfiddle.net/mi7x6k