Given an array in the JSON, I am trying to find the best way to convert it to JArray. For example - consider this below C# code:
var json = @"{
""cities"": [""London"", ""Paris"", ""New York""]
}";
I can read this JSON into JObject as -
var jsonObject = JObject.Parse(json);
Now I will get the "cities" field.
var jsonCities = jsonObject["cities"];
Here I get jsonCities as type JToken
.
I know jsonCities
is an array, so I would like to get it converted to JArray
.
The way I do currently is like this -
var cities = JArray.FromObject(jsonCities);
I am trying to find out is there any better way to get it converted to JArray. How are other folks using it?
As stated by dbc, a JToken that represent a JArray, is already a JArray.
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.
it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.
The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...
The accepted answer should really be the comment by dbc.
After the proposed casting to JArray, we can validate the result by checking for null value:
var jsonCities = jsonObject["cities"] as JArray;
if (jsonCities == null) return;
...do your thing with JArray...
As stated by dbc, a JToken that represent a JArray, is already a JArray.
That is if the JToken.Type equals an JTokenType.Array. If so it can be accessed by using the as JArray
notation. When the as
casting notation is used, a failed cast will render a null
value, as explained here. That makes it convenient for validating that you actually got a JArray you can use.
JArray.FromObject(x)
takes an object
, so it can be used with anything that can be represented as an object
and thus certainly an JToken.
In this case we know that we can simply cast from JToken to JArray, so it gives us another possibility. I would expect it to be faster, but I leave that as an exercise for someone else to figure out.
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