Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonIgnore attribute keeps serializing properties in ASP.NET Core 3

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 .

like image 483
mattinsalto Avatar asked Oct 22 '19 07:10

mattinsalto


People also ask

How can you prevent a property from being serialized?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.

How to ignore Json attribute?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

Can I optionally turn off the JsonIgnore attribute at runtime?

Show activity on this post. Yes, this can be done using a custom ContractResolver .

What is the use of Ignoredatamember in Web API?

NET Core Web Api. When applied to the member of a type, specifies that the member is not part of a data contract and is not serialized. You can fill the id later on in the controller and still maintain one viewmodel.


1 Answers

[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.

like image 169
Tseng Avatar answered Sep 16 '22 18:09

Tseng