JsonIgnore attribute keeps serializing properties in ASP.NET Core 3
Asked Answered
S

3

8

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; }
}

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 .

Springer answered 22/10, 2019 at 7:44 Comment(0)
P
13

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

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

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

services.AddMvc()
    .AddNewtonsoftJson();

or

services.AddControllers()
    .AddNewtonsoftJson();

for WebAPI-esque applications.

Plaice answered 22/10, 2019 at 8:19 Comment(2)
Well even though you might have AddNewtonsoftJson() as a method, it is useless if you don't explicitly add the Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget to your project. Lost an hour finding that out!Malebranche
System.Text.Json has its own built in JsonIgnoreAttribute as well, the same class name. learn.microsoft.com/en-us/dotnet/api/… also available in nuget nuget.org/packages/System.Text.JsonDownbeat
D
3

For your .Net Standard project, grab System.Text.Json package from nuget

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

so you can use

System.Text.Json.Serialization.JsonIgnoreAttribute

instead of

Newtonsoft.Json.JsonIgnoreAttribute
Downbeat answered 27/2, 2020 at 16:45 Comment(0)
P
1

Add the Newtonsoft.json Nuget package if not already installed (this isn't included in .NET Core, so you'll need the Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package)

In program.cs, add NewtonsoftJson as a service:

services.AddMvc()
    .AddNewtonsoftJson();

or

services.AddControllers()
    .AddNewtonsoftJson();

In the entity class add

using Newtonsoft.Json;

Mark the navigation property in the entity class with:

[JsonIgnore]

e.g.

[JsonIgnore]
public MyProperty? MyProperty { get; set; }
Perfumery answered 10/8, 2022 at 3:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.