6

我正在将我的 .net 核心 2.1 转换为 3.0,并从 newtonsoft 升级到内置 JSON 序列化程序。

我有一些设置默认值的代码

[DefaultValue(true)]
[JsonProperty("send_service_notification", DefaultValueHandling = DefaultValueHandling.Populate)]
public bool SendServiceNotification { get; set; }

请帮助我解决 System.Text.Json.Serialization 中的等效问题。

4

1 回答 1

7

问题 #38878: System.Text.Json 选项以忽略序列化和反序列化中的默认值中所述,从 .Net Core 3开始,没有DefaultValueHandlingSystem.Text.Json.

话虽如此,您正在使用DefaultValueHandling.Populate

反序列化时,具有默认值但没有 JSON 的成员将被设置为其默认值。

这可以通过在构造函数或属性初始化器中设置默认值来实现:

//[DefaultValue(true)] not needed by System.Text.Json
[System.Text.Json.Serialization.JsonPropertyName("send_service_notification")]
public bool SendServiceNotification { get; set; } = true;

事实上,文档DefaultValueAttribute建议这样做:

ADefaultValueAttribute不会导致成员使用属性值自动初始化。您必须在代码中设置初始值。

演示小提琴在这里

于 2019-10-24T22:49:09.810 回答