使用 System.Text.Json 反序列化具有私有设置器的属性

Use System.Text.Json to deserialize properties with private setters

有没有办法对包含私有 setter 属性的对象使用 System.Text.Json.JsonSerializer.Deserialize,并填充这些属性? (就像 Newtonsoft.Json 一样)

在 .NET Core 3.x 中,这是不可能的。在 .NET 5 时间轴中,support has been added.

根据 the official docs (C# 9),您有 2 个选项:

  1. 在 属性 上使用 init 而不是 set。例如。 public string Summary { get; init; }

  2. 在具有私有 setter 的属性上添加 JsonInclude 属性。例如

    [JsonInclude] 
    public string Summary { get; private set; }
    

无论哪种方式,JsonSerializer.DeserializeAsync 都会为您完成。