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?
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.
Specifies the settings on a JsonSerializer object.
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; } }
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.
public class Foo
{
public int Bar { get; set;}
public virtual bool ShouldSerializeBar()
{
return true;
}
}
public class Foo2 : Foo
{
public override bool ShouldSerializeBar()
{
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With