How can I convert JToken to string[]?
- Create C# classes from the below json using this tool or in VS
Edit > Paste Special > Paste JSON As Classes
. - Install
Newtonsoft.Json
Nuget package - Use
JsonConvert.DeserializeObject
to deserialize the json to C# classes. - The
root
object now contains everything you've ever wanted!
file.json
{
"Documents": [
{
"id": "961AA6A6-F372-ZZZZ-1270-ZZZZZ",
"ApiKey": "SDKTest",
"ConsumerName": "SDKTest",
"IsAdmin": false,
"Brands": [
"ZZZ"
],
"IsSdkUser": true
}
]
}
Program.cs
using System.IO;
using Newtonsoft.Json;
public class Program
{
static void Main(string[] args)
{
using (StreamReader r = new StreamReader(@"file.json"))
{
string json = r.ReadToEnd();
var root = JsonConvert.DeserializeObject<RootObject>(json);
var brands = root.Documents[0].Brands; // brands = {"ZZZ"}
}
}
}
public class RootObject
{
public Document[] Documents { get; set; }
}
public class Document
{
[JsonProperty("id")]
public string Id { get; set; }
public string ApiKey { get; set; }
public string ConsumerName { get; set; }
public bool IsAdmin { get; set; }
public string[] Brands { get; set; }
public bool IsSdkUser { get; set; }
}
You can use JToken.ToObject<T>()
to deserialize a JToken
to any compatible .Net type, i.e.
var brands = Items.SelectToken("Documents[0].Brands")?.ToObject<string []>();
Casting operations on JToken
such as (bool)Items.SelectToken("Documents[0].IsAdmin")
only work for primitive types for which Newtonsoft has supplied an explicit or implicit conversion operator, all of which are documented in JToken Type Conversions. Since no such conversion operator was implemented for string[]
, deserialization is necessary.
Demo fiddle here.
You can use .Values<T>
to retrieve the values of the JToken
and cast them to the desired type.
var brands = Items["Documents"][0]["Brands"].Values<string>().ToArray();