JsonIgnore属性保留ASP.NET Core 3中的序列化属性 [英] JsonIgnore attribute keeps serializing properties in ASP.NET Core 3

查看:500
本文介绍了JsonIgnore属性保留ASP.NET Core 3中的序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将我的API项目更新为ASP.NET Core3.此后,[JsonIgnore]属性不起作用:

I've recently updated my API project to ASP.NET Core 3. Since then, [JsonIgnore] attributes are not working:

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中有效),因此要在我正在使用Newtonsoft.Json的.NET Standard项目内的模型中使用[JsonIgnore].

All the properties of classes are being serialized. The API endpoints are in .NET Core 3, but all the logic is in .NET Standard 2.1. I have realized that the serializer has changed from Newtonsoft.Json to System.Text.Json. This package is not available in .NET Standard 2.1 (it only works in .NET Core) so to use [JsonIgnore] in Models inside .NET Standard projects I am using Newtonsoft.Json .

推荐答案

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

[JsonIgnore] is an JSON.NET attribute and won't be used by the new System.Text.Json serializer.

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

Since your application is an ASP.NET Core 3.0 System.Text.Json will be used by default. If you want to continue to consume the JSON.NET annotations, you have to use JSON.NET in ASP.NET Core 3

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

It's as easy as adding .AddNewtonsoftJson() to your MVC or WebApi Builder

services.AddMvc()
    .AddNewtonsoftJson();

services.AddControllers()
    .AddNewtonsoftJson();

适用于WebAPI的应用程序.

for WebAPI-esque applications.

这篇关于JsonIgnore属性保留ASP.NET Core 3中的序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆