Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to turn a JArray of type Type into an array of Types?

Tags:

c#

json.net

I've got a JArray that represents the json substring [1,2,3]. I'd like to turn it into an int[] instead.

What's the correct way of doing this? The best way I've found so far is to do the following:

int[] items = new int[myJArray.Count];

int i = 0;
foreach (int item in myJArray)
{
    items[i++] = item;
}
like image 958
moswald Avatar asked Dec 13 '11 17:12

moswald


People also ask

How do I convert JArray to JObject?

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

What is JArray?

JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray) Initializes a new instance of the JArray class from another JArray object.

How do I declare JArray?

JArray addresses = new JArray(); foreach (AddressModel address in contactAddresses) { addresses. Add(JObject. Parse( @"{""street"":""" + address. Street + @"""city"":""" + address.


3 Answers

myJArray.ToObject<int[]>(); 

You can also specify HashSet, List etc.

The accepted answer relies on .NET's conversion - this technique uses JSON.NET's own in addition to what .NET can provide so works with more scenarios.

It's also faster as it isn't using a generator & closure for the LINQ operation.

like image 196
DamienG Avatar answered Sep 19 '22 14:09

DamienG


int[] items = myJArray.Select(jv => (int)jv).ToArray(); 
like image 33
L.B Avatar answered Sep 20 '22 14:09

L.B


A cast needed first for me:

((Newtonsoft.Json.Linq.JArray)myJArray).Select(item => (int)item).ToArray()
like image 28
Ali Gonabadi Avatar answered Sep 21 '22 14:09

Ali Gonabadi