我正在从 .NET Core 3.0 应用程序迁移Newtonsoft.Json
到System.Text.Json
。
如何获得与配置为System.Text.Json
的 .NET Core 2.2 应用程序相同的行为?您可以找到此处描述的选项。Newtonsoft.Json
DefaultValueHandling = DefaultValueHandling.Ignore
DefaultValueHandling
请尝试我作为 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"}
}
我不认为你可以做到这一点,至少不是以一种简单的方式。您可以使用类的属性轻松地忽略null
值,但这只会忽略值并仍然使用默认值序列化整数、布尔值等。你可以在这里找到更多关于类的信息IgnoreVullValues
JsonSerializerOptions
null
JsonSerializerOptions
我认为这可能会有所帮助
services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
有一个提议的 api-suggestion #42635用于忽略已添加到 .NET Core 5.0 版本中的默认值,该版本将于 2020 年 11 月发布。Newtonsoft 目前是唯一值得用于此特定问题的受支持解决方案。