Po chwili poszukiwań, znalazłem to pytanie:
How to inherit the attribute from interface to object when serializing it using JSON.NET
wziąłem kod Jeff Sternal i dodał JsonIgnoreAttribute
wykrywanie, więc wygląda to tak:
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;
}
}
Używanie ten InterfaceContractResolver
w moim JsonSerializerSettings
, wszystkie właściwości, które mają JsonIgnoreAttribute
w dowolnym interfejsie są również ignorowane, nawet jeśli mają JsonPropertyAttribute
(ze względu na kolejność wewnętrzne bloki if
).
Powinieneś dodać to jako odpowiedź i zaakceptować, jeśli rozwiąże problem. – Groo
Zrobiłem to teraz, ale nie mogłem zrobić tego dużo wcześniej, ponieważ nie mogłem zrobić tego mniej niż 8 godzin po moim pytaniu (i ponieważ nie byłem w pracy w weekend). – fero