Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Newton.Json.Linq.JToken to byte[]?

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.

like image 800
afontalv Avatar asked Jul 29 '16 13:07

afontalv


People also ask

Can we convert JToken to JObject C#?

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.

What is JToken in 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.

Is JToken a JArray?

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.

What is JObject and JToken?

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 ...


1 Answers

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 []>());
like image 75
dbc Avatar answered Sep 22 '22 16:09

dbc