I have an interface with a property like this:
public interface IFoo {
// ...
[JsonIgnore]
string SecretProperty { get; }
// ...
}
I want the SecretProperty to be ignored when serializing all implementing classes. But it seems I have to define the JsonIgnore attribute on every implementation of the property. Is there a way to achieve this without having to add the JsonIgnore attribute to every implementation? I didn’t find any serializer setting which helped me.
After a bit of searching, I found this question:
How to inherit the attribute from interface to object when serializing it using JSON.NET
I took the code by Jeff Sternal and added
JsonIgnoreAttributedetection, so it looks like this:Using this
InterfaceContractResolverin myJsonSerializerSettings, all properties which have aJsonIgnoreAttributein any interface are ignored, too, even if they have aJsonPropertyAttribute(due to the order of the innerifblocks).