Serialization 不支持没有无参数构造函数的引用类型的反序列化

Serialization 不支持没有无参数构造函数的引用类型的反序列化,serialization,json-deserialization,.net-core-3.0,Serialization,Json Deserialization,.net Core 3.0,我有这个API public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel) { AddDocumentStatus documentState=\u documentService.AddDocument(documentRequestModel、DocumentType.OutgoingPossipment); 如果(documentState.IsSuccess) 返回Ok()

我有这个API

public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
{
AddDocumentStatus documentState=\u documentService.AddDocument(documentRequestModel、DocumentType.OutgoingPossipment);
如果(documentState.IsSuccess)
返回Ok();
返回请求();
}
这是我的请求模型

公共类AddDocumentRequestModel
{
public AddDocumentRequestModel(int partnerId,列出产品)
{
PartnerId=PartnerId;
产品=产品;
}
[范围(1,int.MaxValue,{0}的ErrorMessage=“值必须介于{1}和{2}之间。”)]
public int PartnerId{get;private set;}
[必需,MustHaveOneElement(ErrorMessage=“至少需要一种产品”)]
公共列表产品{get;private set;}
}
所以当我试着用这个身体来打API的时候

{
“partnerId”:101,
“产品”:[{
“productId”:100,
“测量单位ID”:102,
“数量”:5
}
]
}
这是请求:System.NotSupportedException:不支持无参数构造函数的引用类型的反序列化。键入“Alati.Commerce.Sync.Api.Controllers.AddDocumentRequestModel”


我不需要无参数构造函数,因为它不读取主体参数。还有其他反序列化方法吗?

您可以实现所需的结果。您需要切换到NewtonsoftJson序列化(从包Microsoft.AspNetCore.Mvc.NewtonsoftJson)

在ConfigureServices方法的Startup.cs中调用此函数:

    services.AddControllers().AddNewtonsoftJson();
在此之后,将通过反序列化调用构造函数

额外信息:我正在使用ASP Net Core 3.1

稍后编辑:我想提供更多信息,因为这似乎也可以通过使用System.Text.Json实现,尽管自定义实现是必要的。来自jawa的答案指出,可以通过创建自定义转换器(从JsonConverter继承)并将其注册到转换器集合(JsonSerializerOptions.converts)来使用System.Text.Json实现,如下所示:


使用System.Text.Json仍然存在一些限制-请看这里:
目前还不支持使用参数化构造函数而不使用无参数构造函数的反序列化(但他们计划这样做)。您可以实现自定义JsonConverter(如本例所示:)或-如上面建议的Adrian Nasul:使用Newtonsoft.Json,然后您可以使用[JsonConstructor]属性

此答案在添加包Microsoft.AspNetCore.Mvc.NewtonsoftJsonSome IDE(如Rider)后也为我解决了这个问题将建议您将用于序列化的类转换为抽象类。删除abstract关键字(改用具体类),它将解决此异常的许多其他问题,而不是OP提到的问题。自.NET 5.0起应该可以工作。看见
   public class ImmutablePointConverter : JsonConverter<ImmutablePoint>
   {
   ...
   }
   var serializeOptions = new JsonSerializerOptions();
   serializeOptions.Converters.Add(new ImmutablePointConverter());
   serializeOptions.WriteIndented = true;