Search code examples
c#asp.net-web-apijson.net

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'


I am testing my Web API. Mocking the data I have this:

string json = """
  {
    "PrintId": 10,
    "Header": "header",
    "TC": "tc",
    "CompanyRef": "00000000-0000-0000-0000-000000000000"
  }
  """; 
var objs = ((JArray)JsonConvert.DeserializeObject(json)).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

Solution

  • 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 = //...