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

3
  • Are you able to make a custom model, or use something like JObject.Parse? Commented May 3, 2021 at 13:09
  • Json.NET or System.Text.Json? Commented May 3, 2021 at 13:12
  • Does it answer your question? stackoverflow.com/questions/16079116/… Commented May 3, 2021 at 13:13

2 Answers 2

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}");
}
Sign up to request clarification or add additional context in comments.

3 Comments

That is what I exactly look for. Thanks so much :)
@tymtam Is it possible to change the value of the received JToken?
In what sense change it? Maybe you could ask a separate question with an example showing what you're trying to achieve.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.