How to get key value from nested json object in c#

To get a key value from a nested JSON object in C#, you can use the JSON.NET library. This library provides various methods and classes to parse JSON data easily.

Let’s consider the following example JSON object:

{
  "person": {
    "name": "John Doe",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "New York",
      "state": "NY"
    }
  }
}
  

To access the nested values, you need to parse the JSON string into a JObject:

string json = "{'person':{'name':'John Doe','age':30,'address':{'street':'123 Main St','city':'New York','state':'NY'}}}";
JObject obj = JObject.Parse(json);
  

Now, you can access the nested values using the key names:

string name = (string)obj["person"]["name"];
int age = (int)obj["person"]["age"];
string street = (string)obj["person"]["address"]["street"];
string city = (string)obj["person"]["address"]["city"];
string state = (string)obj["person"]["address"]["state"];
  

In the above code, we are using the indexing operator to access the nested values based on their respective keys.

You can replace the key names with the actual ones present in your JSON object.

Finally, you can use these values as needed in your C# code.

Leave a comment