【问题标题】:ShouldSerialize method is not triggered in .NET Core 3.NET Core 3 中不触发 ShouldSerialize 方法
【发布时间】: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


【解决方案1】:

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

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

要恢复 ShouldSerialize 功能,您可以恢复使用 Newtonsoft,如 this answer 中所示 poke 到 Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0? 以及 Add Newtonsoft.Json-based JSON format support:

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

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddNewtonsoftJson();
    }
    

【讨论】:

    【解决方案2】:

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

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? MyProperty { get; set; }
    

    如果想在 json 中允许可选的 null,可以使用类似于 Nullable 的自定义 Optional&lt;T&gt; 结构,例如one 来自罗斯林。那么结果 JSON 中可能有一个值、null 或根本没有字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2017-10-30
      • 2021-09-14
      • 2021-02-23
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      相关资源
      最近更新 更多