【发布时间】:2020-04-17 20:11:20
【问题描述】:
我通常使用ShouldSerialize 来排除没有数据的属性,例如数组,但现在,当我只在.NET Core 3 中使用 JSON 序列化程序时,它似乎不会被触发。它在使用 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;
}
知道为什么 ShouldSerializeUsers 没有被触发吗?
我看到了其他可以使用的答案:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.NullValueHandling =
NullValueHandling.Ignore;
});
}
但我想知道是否有其他方法可以处理这个问题,因为我没有使用.AddMvc
谢谢。
【问题讨论】:
-
IIUC,来自
System.Text.Json命名空间的内置json序列化器中没有这样的选项,根据sources -
还有一个 GitHub issue 与更改这些选项的可能性有关
-
您需要恢复到 Json.NET 才能使用
ShouldSerializeXXX()功能。为此,请参阅Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?。 -
@dbc 我刚刚尝试恢复到 Json.NET,但是当它尝试将枚举数组序列化为字符串而不是使用
Unable to cast object of type 'System.Text.Json.Serialization.JsonStringEnumConverter' to type 'Newtonsoft.Json.JsonConverter'.时使用值时,我没有收到错误消息所以现在,即使是空的,我也只能忍受在 Json 中定义的数组。现在不重要,但会很好。 -
@dbc 否,但我原来的问题已解决,即恢复为 Json.NET
标签: c# json asp.net-core serialization asp.net-core-webapi