I have a problem with Json.Net when serializing derived objects, which have private properties. Sth like
public class Base
{
[JsonProperty]
private string Type { get { return "Base"; } }
}
public class Inherited : Base
{
[JsonProperty]
private string Type { get { return "Inherited"; } }
}
When I serialize instances of Inherited
, the Type
property is always set to "Base". The only way I've found that work is that the property is protected or public and overriden in subclass.
Why does it work this way? Is that a bug?
Looks like this is an intended behavior of Json.NET. From ReflectionUtils.cs:
This is where the list of properties for a type is generated, and as you can see, there is code that intentionally prefers identically named properties in the base class to the inherited class.
I don't know why Json.NET does this, you might want to report an issue and ask why. In the meantime, you can use an
IContractResolver
to prevent this behavior selectively:I recommend doing this selectively because I don't entirely understand why Json.NET does what it does. The code above only overrides the default behavior for derived class properties with the custom
JsonPreferDerivedPropertyAttribute
attribute applied.And then use it like:
And the outputs are:
and