相当于将我的 newtonsoft 实现转换为 .net core 3.0 中的新 JSON 库期间的默认值

equivalent of default value during Converting my newtonsoft implementation to new JSON library in .net core 3.0

我正在将我的 .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 中的等效问题。

Issue #38878: System.Text.Json option to ignore default values in serialization & deserialization, as of .Net Core 3 there is no equivalent to the DefaultValueHandling functionality in System.Text.Json所述。

也就是说,您正在使用 DefaultValueHandling.Populate:

Members with a default value but no JSON will be set to their default value when deserializing.

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

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

事实上,documentation for DefaultValueAttribute 建议这样做:

A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.

演示 fiddle here.