我可以使用 System.Text.Json 使用私有构造函数反序列化 Json 吗?

Can I deserialize Json with private constructor using System.Text.Json?

想知道是否可以拥有私有构造函数并使用新的 System.Text.Json 序列化程序。

public class MyModel
{
    public string Name { get; set; }
    public string Data { get; set; }

    private MyModel() 
    {
        // use me for when deserializing
    }

    public MyModel(string name, string data)
    {
        Name = name;
        Data = data;
    }
}

一次简单的往返。

var model = new MyModel("doo", "doo");
var json = JsonSerializer.Serialize(model, new JsonSerializerOptions
{
    WriteIndented = true
});

// no to go because of there is no parameterless constructor defined for this object.
var rehydrated = JsonSerializer.Deserialize<MyModel>(json);

会出现the answer is "No," or at least, "Not Yet".

This is a known limitation of the System.Text.Json serializer for [System.Text.Json] v1. We plan to support this in the future. -ashonkhan

You can write a custom converter for this...For the [ASP.NET Core] 3.0 release, there is no planned additional support for calling a non-default constructor during deserialization. That would have to be done by a custom converter. -steveharter

链接的自定义转换器选项将允许您使用 API 您 必须构建对象的任何内容,但与什么不一样,比如说, Newtonsoft.Json 或 Entity Framework 可以通过摆弄反射和私有构造函数来实现,所以可能不是您想要的。

您需要使用 JsonConstructor 属性

检查下面的link

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-immutability?pivots=dotnet-5-0