【问题标题】:equivalent of default value during Converting my newtonsoft implementation to new JSON library in .net core 3.0相当于将我的 newtonsoft 实现转换为 .net core 3.0 中的新 JSON 库期间的默认值
【发布时间】: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


【解决方案1】:

Issue #38878: System.Text.Json option to ignore default values in serialization & deserialization 中所述,从 .Net Core 3 开始,在 System.Text.Json 中没有与 DefaultValueHandling 等效的功能。

话虽如此,你正在使用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;

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

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

演示小提琴here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多