简体   繁体   中英

Error deserializing json with nested arrays

I'm trying to deserialize a json object that includes nested arrays and I get the following error when I try it in Postman:

{ "errors": { "accounts": [ "Cannot deserialize the current JSON array (eg [1,2,3]) into type 'Orders.Dtos.Accounts' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath 'accounts', line 7, position 17." ] }, "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-92466567188264cbdc71e6f6d7479688-fe08150cd947ddf1-00" }

Simplified json to deserialize:

{
   "plannedShippingDateAndTime": "2023-02-07T07:06:00 GMT+01:00",
   "pickup": {
       "isRequested": false
   },
   "productCode": "N",
   "accounts": [
       {
           "typeCode": "shipper",
           "number": "999999999"
       }
   ]

}

Classes:

public class ShipmentData
{
    public string PlannedShippingDateAndTime { get; set; }
    public Pickup Pickup { get; set; }
    public string ProductCode { get; set; } = "N";
    public Accounts Accounts { get; set; }
}

public class Pickup
{
    public bool isRequested { get; set; }
}

public class Accounts
{
    public ArrayAccounts[] ArrayAccounts { get; set; }
}

public class ArrayAccounts
{
    public string TypeCode { get; set; }
    public string Number { get; set; }
}

Api Controller:

[HttpPost("CreateShipment/{OrderId}")]
public async Task<ActionResult> CreateShipment(string OrderId, ShipMentData shipmentData)
{
    ...
}
public class ShipmentData
{
    public string PlannedShippingDateAndTime { get; set; }
    public Pickup Pickup { get; set; }
    public string ProductCode { get; set; }
    public Account[] Accounts { get; set; }
}

public class Pickup
{
    public bool IsRequested { get; set; }
}

public class Account
{
    public string TypeCode { get; set; }
    public string Number { get; set; }
}

Also Customize JSON binding :

options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM