有點搜索之後,我發現這個問題:
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
塊)。
如果它解決了您的問題,您應該添加此答案並接受它。 – Groo 2012-01-13 14:04:27
我現在是這麼做的,但我之前做不了很多事情,因爲在我的問題發生後不到8小時(因爲我週末沒有工作),我不能這樣做。 – fero 2012-01-16 07:59:44