Search code examples
c#jsonjson.net

JsonSerializationException: Cannot create and populate list type


I am dealing with the error:

Newtonsoft.Json.JsonSerializationException: Cannot create and populate list type UpdatePurchaseOrders.SalesOrderSummaryCollection. Path '', line 1, position 1.

The JSON:

[
    {
        "OrderNumber": "017323906",
        "PONumber": "PON023329",
        "DocType": "ZOR",
        "Status": "On Hold",
        "Total": 83899.1600,
        "DateEntered": "3/2/2021 11:05 AM",
        "LastChanged": "3/4/2021 7:19 AM"
    }
]

I have two classes I am testing. The first one is an object with properties matching the JSON.

[JsonArray]
public class SalesOrderSummary
{
    public string OrderNumber { get; set; }
    public string PONumber { get; set; }
    public string DocType { get; set; }
    public string Status { get; set; }
    public float Total { get; set; }
    public string DateEntered { get; set; }
    public string LastChanged { get; set; }
}

The second I'm calling a collection object that just has an array of the first object.

[JsonArray]
public class SalesOrderSummaryCollection 
{
    public SalesOrderSummary[] result { get; set; }
}

I have used this exact concept in another project last year and it worked perfectly fine - without using any JSON attributes.
In this current project I can attempt to deserialize to either class and I get the same error. If I use SalesOrderSummaryCollection and remove the [JsonArray] attribute, then I get the error ending in:

[...] because the type requires a JSON object

which I hesitantly say I understand but I did not receive this error in the last year project I mentioned.
So I don't know why the same concept between two projects is behaving differently or how to resolve this issue.


Solution

  • You JSON contains an array of Objects, so it could be parsed with:

    var parsedArray = JArray.Parse(json);
    

    You're trying t deserialize to an object of type SalesOrderSummaryCollection, which defines and array of SalesOrderSummary objects.
    The JSON doesn't contain any root objects, thus the exception. To deserialize to that object type, your JSON should start with:

    { "result": [ { // Object 1 }, { // Object N } ] }    
    

    It cannot be decorated with [JsonArray], because, well, it's not an array.

    The direct solution is to deserialize to a collection of SalesOrderSummary objects, either List<SalesOrderSummary> or SalesOrderSummary[]:

    var salesOrder = JsonConvert.DeserializeObject<SalesOrderSummary[]>(json);
    // or 
    var salesOrder = JsonConvert.DeserializeObject<List<SalesOrderSummary>>(json);