Given:
class Mammal
{
public int Age { get; set; }
}
class Human : Mammal
{
public string Name { get; set; }
}
class Stuff
{
public Mammal Mammal { get; set; }
}
And
var stuff = new Stuff
{
Mammal = new Human
{
Name = "test",
Age = 12
}
};
Console.WriteLine(JsonConvert.SerializeObject(stuff));
I get:
{"Mammal":{"Name":"test","Age":12}}
But I only want to get properties defined in type statically (meaning that I shouldn’t see the name in the JSON), not runtime-type properties. How to do that?
2
Answers
Use
[JsonIgnore]
:This will print:
You can try extending
DefaultContractResolver
:It simply says – if the object serialized is of type
Human
, serialize it accordingly to the contract of the base classMammal
. Which is exactly what you want. This then should be used like this:Reference: Contract Resolvers