Getting JToken name / key using JSON.net

I have a JSON that looks like

[ { "MobileSiteContent": { "Culture": "en_au", "Key": [ "NameOfKey1" ] } }, { "PageContent": { "Culture": "en_au", "Page": [ "about-us/" ] } } ] 

I parse this as a JArray:

 var array = JArray.Parse(json); 

Then I loop through the array:

 foreach (var content in array) { } 

content is JToken

How can I get the "name" or "key" of each item?

For example, "MobileSiteContent" or "PageContent"

+48
json c #
Jan 08 '14 at 17:18
source share
2 answers

JToken - base class for JObject , JArray , JProperty , JValue , etc. You can use the Children<T>() method to get a filtered list of child JToken that have a specific type, such as JObject . Each JObject has a set of JProperty objects that can be accessed using the Properties() method. For each JProperty you can get its Name . (Of course, you can also get Value if you want, and this is another JToken .)

Combining all this, we have:

 JArray array = JArray.Parse(json); foreach (JObject content in array.Children<JObject>()) { foreach (JProperty prop in content.Properties()) { Console.WriteLine(prop.Name); } } 

Output:

 MobileSiteContent PageContent 
+73
Jan 08 '14 at
source share

The default iterator for JObject is a dictionary that iterates over key / value pairs.

 JObject obj = JObject.Parse(response); foreach (var pair in obj) { Console.WriteLine (pair.Key); } 
+10
May 08 '14 at 11:57
source share



All Articles