I am trying to read an array from a JObject into a string[] but I cannot figure out how.
The code is very simple as below but does not work. Fails with error cannot convert JToken to string[]
JObject Items = jsonSerializer.Deserialize<JObject>(jtr);
string[] brands = null;
brands = (string[])Items.SelectToken("Documents[0].Brands");
The following works when I want to read a simple bool so I know I am in the right place.
IsAdmin = (bool)Items.SelectToken("Documents[0].IsAdmin");
the JObject in Documents[0] looks as follows
{
"id": "961AA6A6-F372-ZZZZ-1270-ZZZZZ",
"ApiKey": "SDKTest",
"ConsumerName": "SDKTest",
"IsAdmin": false,
"Brands": [
"ZZZ"
],
"IsSdkUser": true
}
How can I read that Brands array into my string[] brands?
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 ...
JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.
JObject class has parse method; it parses the JSON string and converts it into a Key-value dictionary object. In the following example, I have used “JObject. Parse” method and retrieved data using key. string jsonData = @"{ 'FirstName':'Jignesh', 'LastName':'Trivedi' }"; var details = JObject.
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.
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