Deserialization of reference types without parameterless constructor is not supported

Yoana Gancheva picture Yoana Gancheva · Dec 5, 2019 · Viewed 12.6k times · Source

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 'Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel'

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

Answer

Adrian Nasui picture Adrian Nasui · Apr 9, 2020

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;