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.
To ignore individual properties, use the [JsonIgnore] attribute. 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.
You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
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 JsonIgnoreAttribute
detection, so it looks like this:
class InterfaceContractResolver : DefaultContractResolver
{
public InterfaceContractResolver() : this(false) { }
public InterfaceContractResolver(bool shareCache) : base(shareCache) { }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var interfaces = member.DeclaringType.GetInterfaces();
foreach (var @interface in interfaces)
{
foreach (var interfaceProperty in @interface.GetProperties())
{
// This is weak: among other things, an implementation
// may be deliberately hiding an interface member
if (interfaceProperty.Name == member.Name && interfaceProperty.MemberType == member.MemberType)
{
if (interfaceProperty.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any())
{
property.Ignored = true;
return property;
}
if (interfaceProperty.GetCustomAttributes(typeof(JsonPropertyAttribute), true).Any())
{
property.Ignored = false;
return property;
}
}
}
}
return property;
}
}
Using this InterfaceContractResolver
in my JsonSerializerSettings
, all properties which have a JsonIgnoreAttribute
in any interface are ignored, too, even if they have a JsonPropertyAttribute
(due to the order of the inner if
blocks).
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