在 Json.Net 中,我们有 JsonConstructor 属性,以指示应该使用构造函数创建对象的反序列化器。
System.Text.Json 中是否有替代方案?
在 Json.Net 中,我们有 JsonConstructor 属性,以指示应该使用构造函数创建对象的反序列化器。
System.Text.Json 中是否有替代方案?
从 .NET 5.0 Preview 8 开始,现在似乎已经添加了这样的内容:
请尝试我作为 System.Text.Json 的扩展编写的这个库以提供多态性:https ://github.com/dahomey-technologies/Dahomey.Json
添加在您的类的命名空间 Dahomey.Json.Attributes 中定义的 [JsonConstructor] 属性。
public class ObjectWithConstructor
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[JsonConstructor]
public ObjectWithConstructor(int id, string name)
{
Id = id;
Name = name;
}
}
通过调用命名空间 Dahomey.Json 中定义的扩展方法 SetupExtensions 来设置 json 扩展。然后使用常规的 Sytem.Text.Json API 反序列化您的类。
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
const string json = @"{""Id"":12,""Name"":""foo"",""Age"":13}";
ObjectWithConstructor obj = JsonSerializer.Deserialize<ObjectWithConstructor>(json, options);