MT467
MT467

Reputation: 698

parsing JSON with Json.Net to get the Key

Searched my question and didnt find the answer, I have a JSON file like below:

{  
   "handle":"ABCD",
   "Tracks":{  
      "Design":{  
         "rating":402
      },
      "Development":{  
         "rating":1584,
         "reliability":"n/a"
      },
      "Specification":{  
         "rating":923,
         "reliability":"0.13"
      },
      "Conceptualization":{  
         "rating":895
      }
   }
}

I am getting a dynamic object of json:

dynamic dynObj;
dynObj = JsonConvert.DeserializeObject(content);

how can I get the name of "Tracks" item? I dont know how many tag like "Design" is there nor I know the name of them...

Upvotes: 0

Views: 83

Answers (1)

Bas
Bas

Reputation: 27105

In your (dynamic) scenario, don't use dynamic, it does not make sense, since you are looking for schema information about the document, which becomes unavailable through the dynamic model.

So, get a JObject by calling JObject.Parse on your JSON data.

Then, get the keys as such (taken from the JObject.Properties documentation):

foreach (var prop in myJObject.Properties()) 
{ 
    //returns 'handle' and 'Tracks' for your root object
    Console.WriteLine("{0} - {1}", prop.Name, prop.Value); 
}

Or using the enumerator of the JObject:

foreach (var kvp in myJOBject) 
{
    Console.WriteLine("{0} - {1}", kvp.Key, kvp.Value);
}

Upvotes: 1

Related Questions