.NET Core 3中未触发ShouldSerialize方法 [英] ShouldSerialize method is not triggered in .NET Core 3
问题描述
我通常使用ShouldSerialize
来排除没有数据的属性,例如数组,但是现在,当我仅在.NET Core 3
中使用JSON序列化程序时,它似乎不会被触发.使用NewtonSoft
时已触发该事件,但由于不再需要它,因此已将其从项目中删除.
I normally use ShouldSerialize
to exclude properties that have no data such as array but now, it does not appear to be triggered when I'm only using JSON serializer in .NET Core 3
. It was being triggered when using NewtonSoft
but I've removed it from my project since it no longer appears to be required.
例如:
private ICollection<UserDto> _users;
public ICollection<UserDto> Users
{
get => this._users ?? (this._users = new HashSet<UserDto>());
set => this._users = value;
}
public bool ShouldSerializeUsers()
{
return this._users?.Count > 0;
}
有什么想法为什么不应该触发ShouldSerializeUsers?
Any ideas why ShouldSerializeUsers is not being triggered?
我看到了其他可以使用的答案:
I've seen other answers where you can use:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling =
NullValueHandling.Ignore;
});
}
但是我想知道是否还有其他方法可以处理此问题,因为我没有使用.AddMvc
But I'd like to know if there is another way to handle this as I'm not using .AddMvc
谢谢.
推荐答案
在ASP.NET Core 3.0中未触发ShouldSerialize
的原因是,在此版本和后续版本的ASP.NET中, a默认情况下,将使用不同的JSON序列化程序,即
The reason that your ShouldSerialize
is not triggered in ASP.NET Core 3.0 is that, in this and subsequent versions of ASP.NET, a different JSON serializer is being used by default, namely System.Text.Json.JsonSerializer
. See:
不幸的是,从.NET Core 3.1开始,此序列化器不支持ShouldSerializeXXX()
模式.如果这样做的话,它会在
Unfortunately as of .NET Core 3.1 this serializer does not support the ShouldSerializeXXX()
pattern; if it did it would be somewhere in JsonSerializer.Write.HandleObject.cs
-- but it's not. The following issues track requests for conditional serialization:
System.Text.Json选项可忽略序列化和安培中的默认值;反序列化#779 .
要恢复ShouldSerialize
功能,您可以还原为使用Newtonsoft,如此答案所示为 .net Core 3.0中IMvcBuilder AddJsonOptions放在哪里? 通过添加基于Newtonsoft.Json的JSON格式支持 :
To restore ShouldSerialize
functionality, you can revert back to using Newtonsoft as shown in this answer to Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0? by poke, and also Add Newtonsoft.Json-based JSON format support:
- 安装
Microsoft.AspNetCore.Mvc.NewtonsoftJson
. -
然后在
Startup.ConfigureServices
中调用AddNewtonsoftJson()
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
这篇关于.NET Core 3中未触发ShouldSerialize方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!