Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft JSON ShouldSerialize and inheritance

I have a class like this:

public class Foo
{
    public int Bar { get; set;}
}

This class is used to be stored in a NoSQL database so I need to store the Bar value. However, I don't want to expose this value through my API. So I created a class that inherits from Foo that I will return from my API.

I created the method ShouldSerializeBar by following the documentation I found here.

public class Foo2 : Foo
{
    public bool ShouldSerializeBar()
    {
        return false;
    }
}

However, the method is not called. Is there a workaround for this or another way to achieve this?

like image 526
Charles Ouellet Avatar asked Feb 07 '17 20:02

Charles Ouellet


People also ask

Is Newtonsoft deprecated?

Despite being deprecated by Microsoft in . NET Core 3.0, the wildly popular Newtonsoft. Json JSON serializer still rules the roost in the NuGet package manager system for . NET developers.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object.

What is JsonProperty C#?

This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }

What is JsonIgnore C#?

Ignore individual properties 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. If no Condition is specified, this option is assumed.


1 Answers

public class Foo
{
    public int Bar { get; set;}

    public virtual bool ShouldSerializeBar()
    {
        return true;
    }
}

public class Foo2 : Foo
{
    public override bool ShouldSerializeBar()
    {
        return false;
    }
}
like image 108
dana Avatar answered Sep 29 '22 20:09

dana