我通常使用ShouldSerialize
排除没有数据(例如数组)的属性,但现在,当我仅在中使用 JSON 序列化器时,它似乎不会被触发.NET Core 3
。使用时被触发NewtonSoft
但我已将其从我的项目中删除,因为它似乎不再需要。
例如:
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;
}
有什么想法为什么ShouldSerialize Users 没有被触发吗?
我看过其他可以使用的答案:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling =
NullValueHandling.Ignore;
});
}
但我想知道是否有另一种方法来处理这个问题,因为我没有使用.AddMvc
Thanks.
原因是你的ShouldSerialize
在 ASP.NET Core 3.0 中不会触发的原因是,在此版本和后续版本的 ASP.NET 中,默认情况下使用不同的 JSON 序列化器,即System.Text.Json.JsonSerializer. See:
-
尝试新的 System.Text.Json API.
-
3.0 中对 Microsoft.AspNetCore.App 的重大更改 #325.
-
.NET Core 3.0 中 JSON 的未来 #90.
不幸的是,从 .NET Core 3.1 开始,这个序列化器不支持ShouldSerializeXXX()
图案;如果确实如此,它会在某个地方JsonSerializer.Write.HandleObject.cs——但事实并非如此。以下问题跟踪条件序列化请求:
恢复ShouldSerialize
功能,您可以恢复使用 Newtonsoft,如下所示这个答案 to IMvcBuilder AddJsonOptions 在.Net Core 3.0 中去了哪里? by poke,并且添加基于 Newtonsoft.Json 的 JSON 格式支持:
- Install Microsoft.AspNetCore.Mvc.NewtonsoftJson.
-
然后打电话AddNewtonsoftJson()
in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)