Ignore property defined in interface when serializing using JSON.net

前端 未结 4 995
一向
一向 2021-01-11 10:47

I have an interface with a property like this:

public interface IFoo {
    // ...

    [JsonIgnore]
    string SecretProperty { get; }

    // ...
}
<         


        
4条回答
  •  佛祖请我去吃肉
    2021-01-11 11:15

    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).

提交回复
热议问题