.NET Core 3 中不会触发 shouldSerialize 方法

Thi*_*rry 4 c# serialization json asp.net-core asp.net-core-webapi

我通常ShouldSerialize用来排除没有数据的属性,例如数组,但现在,当我只在.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;
    }
Run Code Online (Sandbox Code Playgroud)

为什么没有触发 ShouldSerializeUsers 的任何想法?

我已经看到其他可以使用的答案:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddJsonOptions(options => { 
        options.SerializerSettings.NullValueHandling = 
        NullValueHandling.Ignore;
    });
}
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有另一种方法来处理这个问题,因为我没有使用 .AddMvc

谢谢。

dbc*_*dbc 10

ShouldSerialize在 ASP.NET Core 3.0 中没有被触发的原因是,在这个和后续版本的 ASP.NET 中,默认使用不同的 JSON 序列化程序,即System.Text.Json.JsonSerializer. 看:

不幸的是,从 .NET Core 3.1 开始,此序列化程序不支持该ShouldSerializeXXX()模式;如果是这样,它会在某个地方JsonSerializer.Write.HandleObject.cs——但事实并非如此。以下问题跟踪条件序列化的请求:

要恢复ShouldSerialize功能,可以恢复到如图使用Newtonsoft这个答案哪里IMvcBuilder AddJsonOptions在.net核心3.0去?通过poke,并添加基于 Newtonsoft.Json 的 JSON 格式支持

  1. 安装Microsoft.AspNetCore.Mvc.NewtonsoftJson.
  2. 然后调用AddNewtonsoftJson()Startup.ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddNewtonsoftJson();
    }
    
    Run Code Online (Sandbox Code Playgroud)


Ily*_*dik 5

在 Net 5 中可以使用条件JsonIgnore. 它没有为您提供完整的条件选项,但您至少可以排除 null ,我认为这是最常用的情况:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? MyProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果想要在 json 中允许可选的 null,则可以使用Optional<T>类似于 的自定义结构Nullable,例如Roslyn 中的一个。那么结果 JSON 中可能有值、空或根本没有字段。