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;
}
it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.
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.
JArray addresses = new JArray(); foreach (AddressModel address in contactAddresses) { addresses. Add(JObject. Parse( @"{""street"":""" + address. Street + @"""city"":""" + address.
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.
int[] items = myJArray.Select(jv => (int)jv).ToArray();
A cast needed first for me:
((Newtonsoft.Json.Linq.JArray)myJArray).Select(item => (int)item).ToArray()
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