0

This is my actual wrapper code :

 namespace RestApiTO.Wrapper
{
    public class RequestModel<T> : AttributeModel<T>
    {

        public RequestModel(T data)
        {
            Data = data;
        }
        public T Data { get; set; }
    }

    public class AttributeModel<T>
    {
        public AttributeModel()
        {

        }
        public AttributeModel(T data)
        {
            Attributes = data;
        }

        public T Attributes { get; set; }
    }

    public class OrderRequestModel<T> : AttributeModel<T>
    {

        public OrderRequestModel(T attributes, List<Order_items> dataOrderItems)
        {
            this.Attributes = attributes;
            this.Order_detail = dataOrderItems;
        }

        public int CustomerId { get; set; }
        public List<Order_items> Order_detail { get; set; }
    }

}

This is my expected request body :

{
  "data": {
    "attributes": {
        "user_id": 1,
        "order_detail": [
            {
                "product_id": 1,
                "quantity": 1
            },
            {
                "product_id": 2,
                "quantity": 2
            }
        ]
    }
  }
}

This is schema database : Schema database

This is my controller

     [HttpPost]
        public async Task<ActionResult> PostOrders([FromBody]RequestModel<AttributeModel<OrderRequestModel<Order_items>>> orders)
        { 
// do something }

If I'm using this code there is getting error:

Each parameter in constructor 'Void .ctor(System.Guid, System.String, System.String, System.String, System.String)' on type 'xxxxxxx' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.

I want to make my request body as my expected above, but it's more difficult that of my mind.

halfer
  • 19,824
  • 17
  • 99
  • 186
Triooo
  • 5
  • 2
  • https://github.com/dotnet/runtime/issues/43563, https://github.com/dotnet/runtime/issues/42973, and so on? – CodeCaster Feb 11 '21 at 08:54
  • i could be wrong but you seem to be doing something funky for no real reason... have you considered https://json2csharp.com/ – Seabizkit Feb 11 '21 at 19:15

1 Answers1

0

You could add parameterless constructor to your classes. Than during serialization it creates object using this constructor. After that it goes and map request properties to your object properties using setter.

Also here a good explanation how deserealization works and how it is looking for constructors.

Serhii
  • 723
  • 1
  • 4
  • 12