2

在 Json.Net 中,我们有 JsonConstructor 属性,以指示应该使用构造函数创建对象的反序列化器。

System.Text.Json 中是否有替代方案?

4

2 回答 2

1

从 .NET 5.0 Preview 8 开始,现在似乎已经添加了这样的内容:

宣布 .NET 5.0 预览版 8

.NET 5 中的 JsonSerializer 改进

相关问题: JsonSerializer 对不可变类和结构的支持

相关拉取请求: 添加 [JsonConstructor] 并支持使用参数化 ctor 进行反序列化

于 2020-08-28T13:42:03.300 回答
1

请尝试我作为 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);
于 2019-12-08T23:01:46.600 回答