簡體   English   中英

從 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 下面的行)。 它們可以嵌套在任何項目數組中。 我們需要獲取所有此類屬性,例如字典或鍵值對。 感謝幫助。

好吧,代替注釋掉,讓我們建立一個近似的答案。 實際上,更好的方法是將 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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM