I have a json file like this:
{
"foo": "bar",
"1": 0,
"array": [
"foo",
"bar"
]
}
and I can access "foo" and "1" like this:
using Newtonsoft.Json
JObject o = JObject.Parse(json)
Console.WriteLine((string)o["foo"]) // prints "bar"
Console.WriteLine((int)o["1"]) // prints 0
But how can I access the array? I need a string array string[]
.
CodePudding user response:
JArray jsonArray = (JArray)o["array"];
string[] stringArray = jsonArray.ToObject<string[]>();
- The indexer operator of
JObject
returns aJToken
which needs to be converted toJArray
- You can call the
ToObject
on it where you can specify the return type as string array
UPDATE #1
Well, you don't need to explicitly cast JToken
to JArray
, since the ToObject
is defined on the JToken
. So the following code would be enough:
var stringArray = o["array"].ToObject<string[]>();
CodePudding user response:
You can gain access to the array (an instance of JArray
) by using:
JArray arr = (JArray)o["array"];
To iterate over it's elements, you can use the array's Children
method.
Complete code example:
using System;
using Newtonsoft.Json.Linq;
namespace ConsoleAppCS
{
class Program
{
static void Main(string[] args)
{
string jsonStr = "{ \"foo\": \"bar\", \"1\": 0, \"array\": [ \"foo\", \"bar\" ] }";
JObject o = JObject.Parse(jsonStr);
Console.WriteLine((string)o["foo"]); // prints "bar"
Console.WriteLine((int)o["1"]); // prints 0
JArray arr = (JArray)o["array"];
foreach (var elem in arr.Children())
{
Console.WriteLine((string)elem); // print the array element
}
}
}
}
Output:
bar
0
foo
bar
CodePudding user response:
You can get a string array from the JArray by using:
o["array"].Select(x => x.Value<string>()).ToArray()