Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the name / key of a JToken with JSON.net

Tags:

json

c#

json.net

I have some JSON that looks like this

[   {     "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 over the array:

foreach (var content in array) {  } 

content is a JToken

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

For example, "MobileSiteContent" or "PageContent"

like image 621
Alex Avatar asked Jan 08 '14 17:01

Alex


People also ask

How do I get JToken properties?

JToken is the base class for JObject , JArray , JProperty , JValue , etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject . Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method.

Is a JObject a JToken?

So you see, a JObject is a JContainer , which is a JToken . Here's the basic rule of thumb: If you know you have an object (denoted by curly braces { and } in JSON), use JObject.

Is JToken a JArray?

As stated by dbc, a JToken that represent a JArray, is already a JArray. That is if the JToken. Type equals an JTokenType.


1 Answers

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together 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 
like image 196
Brian Rogers Avatar answered Sep 29 '22 06:09

Brian Rogers