3 回答

TA貢獻1797條經驗 獲得超6個贊
.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;
}
}

TA貢獻1773條經驗 獲得超3個贊
答案似乎是“否”,或者至少是“還沒有”。
這是[System.Text.Json]?v1的 System.Text.Json 序列化程序的已知限制。我們計劃將來支持這一點。?-阿松汗
您可以為此編寫一個自定義轉換器...對于[ASP.NET Core]?3.0 版本,沒有計劃在反序列化期間調用非默認構造函數的額外支持。這必須由定制轉換器來完成。——史蒂夫哈特
鏈接的自定義轉換器選項將允許您使用您所擁有的任何 API 來構建對象,但與 Newtonsoft.Json 或實體框架通過擺弄反射和私有構造函數可以完成的操作不同,所以可能不是你在尋找什么。
- 3 回答
- 0 關注
- 185 瀏覽
添加回答
舉報