2012-01-13 47 views
10

序列化時忽略接口定義的屬性我有一個接口,這樣的特性:使用JSON.net

public interface IFoo { 
    // ... 

    [JsonIgnore] 
    string SecretProperty { get; } 

    // ... 
} 

我想SecretProperty序列化所有執行類時被忽略。但似乎我必須在每個屬性的實現上定義JsonIgnore屬性。有沒有辦法實現這一點,而不必將JsonIgnore屬性添加到每個實現?我沒有找到任何幫助我的序列化程序設置。

+0

如果它解決了您的問題,您應該添加此答案並接受它。 – Groo 2012-01-13 14:04:27

+0

我現在是這麼做的,但我之前做不了很多事情,因爲在我的問題發生後不到8小時(因爲我週末沒有工作),我不能這樣做。 – fero 2012-01-16 07:59:44

回答

5

有點搜索之後,我發現這個問題:

How to inherit the attribute from interface to object when serializing it using JSON.NET

我把代碼由Jeff胸骨並添加JsonIgnoreAttribute檢測,所以它看起來是這樣的:

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塊)。

1

我發現創建一個只有我想要的屬性的DTO並將該對象序列化爲JSON是最簡單的。它創建了許多小的,特定於上下文的對象,但管理代碼庫更容易,我不必考慮我正在序列化什麼和我忽略什麼。

-1

您應該在類名前添加[DataContract]

它將默認值從包括所有屬性更改爲只包括明確標記的屬性。之後,在要包含在JSON輸出中的每個屬性前添加'[DataMember]'。

+0

這絕對不是我想要的。我想讓接口中的忽略定義傳遞到類層次結構的頂部,以便序列化程序將忽略我的接口屬性。我不希望該屬性在接口的任何實現中可序列化。 – fero 2013-11-18 07:38:23