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"
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.
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.
As stated by dbc, a JToken that represent a JArray, is already a JArray. That is if the JToken. Type equals an JTokenType.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With