从 JSON 获取特定数据

Get specific data from a JSON

假设有一个JSON结构如下

{
  "v": "2021",
  "Outeritems": [
    {
      "items": [
        {
          "c": "r",
          "KeyOne": "DataOne",
          "KeyTwo": "DataTwo",
          "items": [
            {
              "c": "r",
              "KeyOne": "DataThree",
              "KeyTwo": "DataFour",
              "v": "F",
              "h": "N",
              "l": "N:"
            },
            {
              "c": "r",
              "KeyOne": "DataFive",
              "KeyTwo": "DataSix",
              "v": "T"
            }
          ]
        }
      ]
    }
  ]
}

如何使用 linq 或某种方法读取所有 KeyOne 及其对应的 KeyTwo(KeyOne 下面的行)。它们可以嵌套在任何 items 数组中。我们需要获取所有诸如字典或键值对之类的属性。感谢您的帮助。

好吧,让我们构建一个近似答案,而不是注释掉。 实际上,更好的方法是将 JSON 反序列化为仅具有相关属性的 class,而不是尝试使用所有 JSON 结构。

喜欢:

    private class Item
    {
        [JsonProperty("KeyOne")]
        public string KeyOne { get; set; }
        [JsonProperty("KeyTwo")]
        public string KeyTwo { get; set; }
        [JsonProperty("items")]
        public List<Item> Items { get; set; }
    }

    private class Outeritem
    {
        [JsonProperty("items")]
        public List<Item> Items { get; set; }
    }

    private class Root
    {
        [JsonProperty("Outeritems")]
        public List<Outeritem> Outeritems { get; set; }
    }

然后像这样反序列化:

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);

然后对于树的横向你可以使用递归方法(只是因为 JSON 字符串是一个相当有限的结构,在所有情况下都不是一个好的方法)

List<string> KeyOneValues = new List<string>();
List<string> KeyTwoValues = new List<string>();
trasverseNode(List<Item> item)
{
  if (item.KeyOne != null) KeyOneValues.Add(item.KeyOne);
  if (item.KeyTwo != null) KeyTwoValues.Add(item.KeyTwo);
  foreach (Item child in item.Items)
  {
    trasverseNode(child); //<-- recursive
  }
}