Kam*_*hid 4 c# json.net .net-core-3.0 system.text.json
我正在将我的 .net core 2.1 转换为 3.0,并从 newtonsoft 升级到内置的 JSON 序列化程序。
我有一些设置默认值的代码
[DefaultValue(true)]
[JsonProperty("send_service_notification", DefaultValueHandling = DefaultValueHandling.Populate)]
public bool SendServiceNotification { get; set; }
Run Code Online (Sandbox Code Playgroud)
请帮我解决 System.Text.Json.Serialization 中的等效项。
正如指出的问题#38878:System.Text.Json选择忽略序列化和反序列化的默认值,作为对.NET核心3有没有相当于DefaultValueHandling
在功能上System.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;
Run Code Online (Sandbox Code Playgroud)
事实上,文档DefaultValueAttribute
建议完全这样做:
A
DefaultValueAttribute
不会导致使用属性值自动初始化成员。您必须在代码中设置初始值。
演示小提琴在这里。
归档时间: |
|
查看次数: |
1434 次 |
最近记录: |