4

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

如何获得与配置为System.Text.Json的 .NET Core 2.2 应用程序相同的行为?您可以找到此处描述的选项。Newtonsoft.JsonDefaultValueHandling = DefaultValueHandling.IgnoreDefaultValueHandling

4

4 回答 4

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"}
}
于 2019-12-11T22:33:17.953 回答
2

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

于 2019-10-03T21:01:59.907 回答
1

我认为这可能会有所帮助

services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
于 2019-10-03T20:58:33.137 回答
0

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

于 2019-11-22T16:52:13.790 回答