使用JSON.net进行序列化时,请忽略接口中定义的属性 [英] Ignore property defined in interface when serializing using JSON.net

查看:75
本文介绍了使用JSON.net进行序列化时,请忽略接口中定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口,其属性如下:

I have an interface with a property like this:

public interface IFoo {
    // ...

    [JsonIgnore]
    string SecretProperty { get; }

    // ...
}

我希望在序列化所有实现类时忽略SecretProperty.但是似乎我必须在该属性的每个实现上定义JsonIgnore属性.有没有一种方法可以不必在每个实现中都添加JsonIgnore属性?我找不到任何对我有用的序列化程序设置.

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:

如何继承使用JSON.NET序列化接口时从接口到对象的属性

我采用了Jeff Sternal的代码,并添加了JsonIgnoreAttribute检测,因此看起来像这样:

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;
    }
}

在我的JsonSerializerSettings中使用此InterfaceContractResolver,在任何接口中都具有JsonIgnoreAttribute的所有属性也将被忽略,即使它们具有JsonPropertyAttribute(由于内部if块的顺序也是如此) ).

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

这篇关于使用JSON.net进行序列化时,请忽略接口中定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆