我正在将.NET Core 3.0应用程序中的Newtonsoft.Json
迁移到System.Text.Json
。
如何使用System.Text.Json
实现与我在.NET Core 2.2应用程序中使用Newtonsoft.Json
配置为DefaultValueHandling = DefaultValueHandling.Ignore
相同的行为? 您可以在此处找到有关DefaultValueHandling
选项的描述.
我正在将.NET Core 3.0应用程序中的Newtonsoft.Json
迁移到System.Text.Json
。
如何使用System.Text.Json
实现与我在.NET Core 2.2应用程序中使用Newtonsoft.Json
配置为DefaultValueHandling = DefaultValueHandling.Ignore
相同的行为? 您可以在此处找到有关DefaultValueHandling
选项的描述.
我认为你无法轻松地做到这一点。你可以使用JsonSerializerOptions
类的IgnoreVullValues
属性轻松地忽略null
值,但这只会忽略null
值,并使用默认值序列化整数、布尔值等。
你可以在这里找到更多关于JsonSerializerOptions
类的信息。
Newtonsoft.Json
。 - stevousing 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扩展。然后使用常规的System.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"}
}
services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
有一个建议的 API 建议#42635,用于忽略默认值,已经添加到 .NET Core 5.0 发布中,该版本将于 2020 年 11 月发布。目前,Newtonsoft 是唯一值得使用的支持解决此特定问题的解决方案。
System.ComponentModel.DefaultValueAttribute
?如果不需要,请参阅与此相关的问题 如何使用 System.Text.Json 忽略 false 值 的此答案。 - dbc