I am attempting to retrieve a byte array from a Jtoken:
byte[] PDF;
var results = JsonConvert.DeserializeObject<dynamic>(jsonData);
if (results != null)
{
JArray docList = (JArray)results.SelectToken("");
foreach (JToken doc in docList)
{
PDF = string.IsNullOrEmpty(doc["PDF"].ToString()) ? null : doc["PDF"];
}
}
But I am receiving this error: "cannot implicitly convert type 'newtonsoft.json.linq.Jtoken to byte[]. An explicit conversion exists (are you missing a cast?)"
How can I convert Newton.Json.Linq.JToken to byte[]?
Thank you.
How can I Convert a JToken To JObject? JObject is a subclass of JToken , so if payload is in fact a JObject , you can just cast it.
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.
JToken. Creates a JArray from an object. The object that will be used to create JArray. The JsonSerializer that will be used to read the object.
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 ...
Use the explicit conversion operator provided for JToken
:
PDF = (byte [])(string.IsNullOrEmpty(doc["PDF"].ToString()) ? null : doc["PDF"]);
Or, use ToObject<T>()
:
PDF = (doc["PDF"] == null ? null : doc["PDF"].ToObject<byte []>());
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