afontalv afontalv - 4 months ago 41
JSON Question

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.

dbc dbc
Answer

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 []>());