Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert Newtonsoft JSON's JToken to JArray?

Tags:

c#

json.net

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?

like image 959
tyrion Avatar asked Oct 18 '17 16:10

tyrion


People also ask

Is JToken a JArray?

As stated by dbc, a JToken that represent a JArray, is already a JArray.

How can I get JProperty from JToken?

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.

How do I convert JArray to JObject?

it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.

What is JObject and JToken?

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 ...


1 Answers

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...

Edit:

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.

like image 92
pekaaw Avatar answered Sep 19 '22 13:09

pekaaw