在JSON对象中递归选择子对象

时间:2019-03-12 12:24:50

标签: c# json.net

如何选择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": []
            }
          ]
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

您可以像这样使用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