假設有一個像下面這樣的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陣列中。我們需要獲取所有這樣的屬性,例如字典或鍵值對。感謝幫助。
uj5u.com熱心網友回復:
好吧,而不是注釋掉,讓我們建立一個近似的答案。實際上,更好的方法是將 JSON 反序列化為僅具有相關屬性的類,而不是嘗試使用所有 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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395913.html
下一篇:輸入陣列的震動以命名陣列的值對
