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

前端 未结 3 1829
-上瘾入骨i
-上瘾入骨i 2020-12-17 09:46

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

var objs = ((JArray)JsonConvert.DeserializeObject(\"{ \\\"PrintId\\\":10,\\\"Header\\\":\\\"header\\\"         


        
3条回答
  •  臣服心动
    2020-12-17 10:00

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

提交回复
热议问题