I am testing my Web API. Mocking the data I have this:
var objs = ((JArray)JsonConvert.DeserializeObject("{ \"PrintId\":10,\"Header\":\"header\",\"TC\":\"tc\",\"CompanyRef\":\"00000000-0000-0000-0000-000000000000\"}")).Values<JObject>();
Which gives me the error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'
The thing is it was working. I must have changed something, but I don't know what.
My intent is to convert this JSON object to a list of .NET objects called Print
which has the fields:
PrintId Header TX CompnayRef
JArray() Initializes a new instance of the JArray class. JArray(Object) Initializes a new instance of the JArray class with the specified content. JArray(Object[])
Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
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.
Just make a class and deserialize it.
public class Print { public int PrintId { get; set; } public string Header { get; set; } public string TC { get; set; } public string CompanyRef { get; set; } } Print printObj = JsonConvert.DeserializeObject<Print>(yourJson); printObj.PrintId = //...
As the message says, your object is JObject
so don't cast it to JArray
. Try this:
var objs = JsonConvert.DeserializeObject("{ \"PrintId\":10,\"Header\":\"header\",\"TC\":\"tc\",\"CompanyRef\":\"00000000-0000-0000-0000-000000000000\"}");
Update To get a collection List<Print>
, your JSON needs to be an array. Try this (I made your JSON an array and added a second object):
string json = "[{ \"PrintId\":10,\"Header\":\"header\",\"TC\":\"tc\",\"CompanyRef\":\"00000000-0000-0000-0000-000000000000\"}" + ",{ \"PrintId\":20,\"Header\":\"header2\",\"TC\":\"tc2\",\"CompanyRef\":\"00000000-0000-0000-0000-000000000000\"}]"; var objs = JsonConvert.DeserializeObject<List<Print>>(json); //The loop is only for testing. Replace it with your code. foreach(Print p in objs){ Console.WriteLine("PrintId: " + p.PrintId); Console.WriteLine("Header: " + p.Header); Console.WriteLine("TC: " + p.TC); Console.WriteLine("CompanyRef: " + p.CompanyRef); Console.WriteLine("=============================="); } public class Print { public int PrintId { get; set; } public string Header { get; set; } public string TC { get; set; } public string CompanyRef { get; set; } }
Here is a fiddle.
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