【发布时间】:2020-02-19 08:56:47
【问题描述】:
我正在将我的 .net core 2.1 转换为 3.0,并从 newtonsoft 升级到内置 JSON 序列化程序。
我有一些设置默认值的代码
[DefaultValue(true)]
[JsonProperty("send_service_notification", DefaultValueHandling = DefaultValueHandling.Populate)]
public bool SendServiceNotification { get; set; }
请帮我解决 System.Text.Json.Serialization 中的等效问题。
【问题讨论】:
-
System.Text.Json中尚不存在直接等效项,请参阅System.Text.Json option to ignore default values in serialization & deserialization #38878。但是,要重现DefaultValueHandling.Populate,您始终可以在构造函数中设置默认值。 -
我有一个实现,如果在发布的 json 中有人没有发送该属性,我认为它是真的,否则如果有人发送它,它可以是真实的或错误的发布
-
那么如果你做
public bool SendServiceNotification { get; set; } = true;,就够了吗? -
感谢 dbc。构造函数相关的事情已经奏效。但是如果在新的 System.Text.Json 中添加类似的属性可能会更好,以便可以轻松移植
标签: c# json.net .net-core-3.0 system.text.json