1

Hello I have one json object which includes nested data such as below

{
"key1":"test",
"key2":{
  "key3" :"test2"
 }
}

and I have one List like below

  List<string> listkeys=  new List<string>() {"key1","key2.key3" }

I want to enter loop of listkeys and get value from json object dynamically.

foreach (int element in listkeys)
{
    //how can I get value with element
}

I couldn't find any solution.

Thanks in advance

mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54

2 Answers2

1

For Json.NET I recommend SelectToken. Please see Querying JSON with SelectToken.

foreach (var element in listkeys) // btw. var/string, not `int`
{
    JToken j = o.SelectToken($"$..{element}");
}
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

Assuming that you are using JSON.net to parse Json, you can do it this way.

foreach (string element in listkeys) // Quick fix, listkeys stores strings, not integers
{
    string[] keys = element.split("."); // "key2.key3" => ["key2", "key3"]
    JObject obj = <jsonObject>;
    foreach (string key in keys) // When key = "key2", obj = <jsonObject>["key2"], when key = "key3", obj = <jsonObject>["key2"]["key3"]
        obj = obj[key];
    <do something with obj>
}

Just replace the jsonObject with the Json object of yours.