在ASP.Net Core 2.2中使用JSON.Net时,当序列化为JSON时,如果其值为null,则我可以忽略该属性:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? Created { get; set; }
但是当使用新的内置JSON(System.Text.Json)的ASP.Net Core 3.0时,如果该属性的值为null,我找不到等效的属性来忽略该属性。
我只能找到JsonIgnore。
我想念什么吗?
答案 0 :(得分:15)
我正在查看.Net Core 3.1,该位置应忽略空值
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
注意,以上内容不是针对每个属性/属性的,尽管有一个属性可能会有所帮助JsonIgnoreAttribute
解决问题的另一种方法是JsonConverterAttribute,有关如何编写自己的转换器的信息为here
答案 1 :(得分:10)
如果要在JSON序列化过程中进行属性级控制以忽略空值,则对于Net Core 3.1,您必须编写一个自定义转换器。 examples described中有Newtonsoft.Json migration documentation。
对于使用Newtonsoft.Json进行声明的功能,这是一个很大的麻烦。您可以通过specifying as much in Startup.ConfigureServices()指定使用Newtonsoft.Json。
services.AddControllers()
.AddNewtonsoftJson();
如文档所述,您需要添加Microsoft.AspNetCore.Mvc.NewtonsoftJson程序包。
答案 2 :(得分:5)
如果您仍在.net core 3.1中使用Newtonsoft.Json,则希望具有以下配置。
services
.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
答案 3 :(得分:5)
此问题已在 .Net 5 上修复
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
查看下面的更新
答案 4 :(得分:2)
将其添加到启动中应该会有所帮助,尽管它不是每个属性也不是一个属性。
services.AddMvc()
.AddJsonOptions(options =>{ options.JsonSerializerOptions.IgnoreNullValues = true; });
答案 5 :(得分:-3)
请参阅官方迁移指南Migrate from ASP.NET Core 2.2 to 3.0
您的服务代码应如下所示:
services.AddMvc(c =>
{
})
.AddNewtonsoftJson(
options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
options.SerializerSettings.Error = (object sender, ErrorEventArgs args) =>
{
// handle error
};
}
);