【问题标题】:JsonIgnore attribute keeps serializing properties in ASP.NET Core 3JsonIgnore 属性不断序列化 ASP.NET Core 3 中的属性
【发布时间】:2020-02-18 07:30:37
【问题描述】:

我最近将我的 API 项目更新为 ASP.NET Core 3。从那时起,[JsonIgnore] 属性就不起作用了:

public class Diagnostico
{
    [JsonIgnore]
    public int TipoDiagnostico { get; set; }

    [JsonIgnore]
    public int Orden { get; set; }

    [JsonIgnore]
    public DateTime? FechaInicio { get; set; }

    public string TipoCodificacion { get; set; }

    public string Codigo { get; set; }

    public string Descripcion { get; set; }
}

类的所有属性都被序列化了。 API 端点在 .NET Core 3 中,但所有逻辑都在 .NET Standard 2.1 中。我意识到序列化程序已从 Newtonsoft.Json 更改为 System.Text.Json。此包在 .NET Standard 2.1 中不可用(它仅适用于 .NET Core),因此要在我正在使用的 .NET Standard 项目中的模型中使用 [JsonIgnore] Newtonsoft.Json

【问题讨论】:

    标签: c# json asp.net-core json.net asp.net-core-3.0


    【解决方案1】:

    [JsonIgnore] 是 JSON.NET 属性,不会被新的 System.Text.Json 序列化程序使用。

    由于您的应用程序是 ASP.NET Core 3.0,默认情况下将使用 System.Text.Json。如果要继续使用 JSON.NET 注释,则必须在 ASP.NET Core 3 中使用 JSON.NET

    就像将.AddNewtonsoftJson() 添加到您的 MVC 或 WebApi Builder 一样简单

    services.AddMvc()
        .AddNewtonsoftJson();
    

    services.AddControllers()
        .AddNewtonsoftJson();
    

    适用于 WebAPI 式应用程序。

    【讨论】:

    • 好吧,即使您可能将 AddNewtonsoftJson() 作为一种方法,但如果您没有将 Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget 显式添加到您的项目中,它也是没有用的。花了一个小时才发现!
    • System.Text.Json 也有自己的内置 JsonIgnoreAttribute,类名相同。 docs.microsoft.com/en-us/dotnet/api/… 也可用于 nuget nuget.org/packages/System.Text.Json
    【解决方案2】:

    对于您的 .Net Standard 项目,从 nuget 获取 System.Text.Json 包

    https://www.nuget.org/packages/System.Text.Json

    因此您可以使用 System.Text.Json.Serialization.JsonIgnoreAttribute 而不是 Newtonsoft.Json.JsonIgnoreAttribute。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多