Suppose there is a json structure like below
{
"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"
}
]
}
]
}
]
}
How can I read all KeyOne and its corresponding KeyTwo(line below KeyOne) using linq or some method. They may be nested in any of items array. We need to get all such properties as a dictionary or key value pair like that. Thanks for help.
CodePudding user response:
Well instead commenting out, lets build an aprox answer. Actually the better aproach is deserialize the JSON to a class with only the relevant properties, instead trying to use all the JSON structure.
Like:
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; }
}
Then deserialize like:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Then for transverse the tree you can use a recursive aproach (just because a JSON string is a rather finite structure, not a good aproach in ALL cases)
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
}
}