.NET 8.0 中的更新
只需添加JsonConstructorAttribute
私有构造函数如下:
public class Employee
{
[JsonConstructor] // This will work from .NET 8.0
private Employee()
{
}
private Employee(int id, string name)
{
Id = id;
Name = name;
}
[JsonInclude]
public int Id { get; private set; }
[JsonInclude]
public string Name { get; private set; }
public static Employee Create(int id, string name)
{
Employee employee = new Employee(id, name);
return employee;
}
}
.NET 7.0 中的更新
从 .NET 7.0 开始,可以通过编写自己的 ContractResolver 使用私有无参数构造函数来完成反序列化,如下所示:
public class PrivateConstructorContractResolver : DefaultJsonTypeInfoResolver
{
public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
JsonTypeInfo jsonTypeInfo = base.GetTypeInfo(type, options);
if (jsonTypeInfo.Kind == JsonTypeInfoKind.Object && jsonTypeInfo.CreateObject is null)
{
if (jsonTypeInfo.Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Length == 0)
{
// The type doesn't have public constructors
jsonTypeInfo.CreateObject = () =>
Activator.CreateInstance(jsonTypeInfo.Type, true);
}
}
return jsonTypeInfo;
}
}
使用方法如下:
private static void Main(string[] args)
{
JsonSerializerOptions options = new JsonSerializerOptions
{
TypeInfoResolver = new PrivateConstructorContractResolver()
};
Employee employee = Employee.Create(1, "Tanvir");
string jsonString = JsonSerializer.Serialize(employee);
Employee employee1 = JsonSerializer.Deserialize<Employee>(jsonString , options);
}
public class Employee
{
private Employee()
{
}
private Employee(int id, string name)
{
Id = id;
Name = name;
}
[JsonInclude]
public int Id { get; private set; }
[JsonInclude]
public string Name { get; private set; }
public static Employee Create(int id, string name)
{
Employee employee = new Employee(id, name);
return employee;
}
}