serializationjson-deserialization.net-core-3.0

Deserialization of reference types without parameterless constructor is not supported


I have this API

 public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
        {
            AddDocumentStatus documentState = _documentService.AddDocument(documentRequestModel, DocumentType.OutgoingPosShipment);
            if (documentState.IsSuccess)
                return Ok();

            return BadRequest();
        }

And this is my request model

    public class AddDocumentRequestModel
    {
        public AddDocumentRequestModel(int partnerId, List<ProductRequestModel> products)
        {
            PartnerId = partnerId;
            Products = products;
        }

        [Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
        public int PartnerId { get; private set; }

        [Required, MustHaveOneElement(ErrorMessage = "At least one product is required")]
        public List<ProductRequestModel> Products { get; private set; }
    }

so when I'm trying to hit the API with this body

{
        "partnerId": 101,
        "products": [{
            "productId": 100,
            "unitOfMeasureId": 102,
            "quantity":5
        }
     ]
}

this is the request:

System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'Sync.Api.Controllers.AddDocumentRequestModel'

I don't need a parameterless constructor, because it doesn't read the body parameters. Is there any other way for deserialization?


Solution

  • You can achieve your desired result. You need to switch to NewtonsoftJson serialization (from package Microsoft.AspNetCore.Mvc.NewtonsoftJson)

    Call this in Startup.cs in the ConfigureServices method:

    services.AddControllers().AddNewtonsoftJson();
    

    After this, your constructor will be called by deserialization.

    Extra info: I am using ASP Net Core 3.1

    Later Edit: I wanted to give more info on this, as it seems that this can also be achieved by using System.Text.Json, although custom implementation is necessary. The answer from jawa states that Deserializing to immutable classes and structs can be achieved with System.Text.Json, by creating a custom converter (inherit from JsonConverter) and registering it to the converters collection (JsonSerializerOptions.Converters) like so:

    public class ImmutablePointConverter : JsonConverter<ImmutablePoint>
    {
    ...
    }
    

    and then...

    var serializeOptions = new JsonSerializerOptions();
    serializeOptions.Converters.Add(new ImmutablePointConverter());
    serializeOptions.WriteIndented = true;