【问题标题】:What is the equivalent of Newtonsoft.Json DefaultValueHandling = DefaultValueHandling.Ignore option in System.Text.JsonSystem.Text.Json 中的 Newtonsoft.Json DefaultValueHandling = DefaultValueHandling.Ignore 选项的等价物是什么
【发布时间】:2020-02-02 04:48:51
【问题描述】:

我正在 .NET Core 3.0 应用程序中从 Newtonsoft.Json 迁移到 System.Text.Json

我如何获得与System.Text.Json 相同的行为,就像我在配置Newtonsoft.JsonDefaultValueHandling = DefaultValueHandling.Ignore 的.NET Core 2.2 应用程序中一样?您可以找到here 中描述的DefaultValueHandling 选项。

【问题讨论】:

标签: c# json .net-core json.net system.text.json


【解决方案1】:

我不认为你可以做到这一点,至少不是以简单的方式。您可以使用JsonSerializerOptions 类的IgnoreVullValues 属性轻松忽略null 值,但这只会忽略null 值,并且仍然使用默认值序列化整数、布尔值等。 你可以找到更多关于JsonSerializerOptionshere

【讨论】:

  • 感谢@byczu 的回答!恐怕你是对的。我可能需要切换回Newtonsoft.Json
【解决方案2】:

请尝试我作为 System.Text.Json 的扩展编写的这个库,以提供缺少的功能:https://github.com/dahomey-technologies/Dahomey.Json

您会发现支持忽略默认值:

using Dahomey.Json;
using Dahomey.Json.Attributes;
using System.Text.Json;

public class ObjectWithDefaultValue
{
    [JsonIgnoreIfDefault]
    [DefaultValue(12)]
    public int Id { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue("foo")]
    public string FirstName { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue("foo")]
    public string LastName { get; set; }

    [JsonIgnoreIfDefault]
    [DefaultValue(12)]
    public int Age { get; set; }
}

通过在命名空间 Dahomey.Json 中定义的扩展方法 SetupExtensions 调用 JsonSerializerOptions 来设置 json 扩展: 然后用常规的 Sytem.Text.Json API 序列化你的类:

public void Test()
{
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.SetupExtensions();

    ObjectWithDefaultValue obj = new ObjectWithDefaultValue
    {
        Id = 13,
        FirstName = "foo",
        LastName = "bar",
        Age = 12
    };

    string json = JsonSerializer.Serialize(obj, options); // {"Id":13,"LastName":"bar"}
}

【讨论】:

    【解决方案3】:

    我认为这会有所帮助

    services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
    

    【讨论】:

    • 谢谢@Gökten Karadağ!它确实有帮助,但您仍然会得到所有错误值。
    【解决方案4】:

    有一个建议的 api-suggestion #42635 用于忽略已添加到 .NET Core 5.0 版本中的默认值,该版本将于 2020 年 11 月发布。Newtonsoft 目前是唯一值得用于此特定问题的受支持解决方案。

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2022-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      相关资源
      最近更新 更多