有没有办法忽略Json.NET中一个我没有权限修改/扩展的类上的[JsonIgnore]
属性?
public sealed class CannotModify
{
public int Keep { get; set; }
// I want to ignore this attribute (and acknowledge the property)
[JsonIgnore]
public int Ignore { get; set; }
}
我需要这个类中的所有属性进行序列化/反序列化。我尝试了子类化Json.NET的DefaultContractResolver类,并覆盖了似乎是相关方法的部分:
public class JsonIgnoreAttributeIgnorerContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
// Serialize all the properties
property.ShouldSerialize = _ => true;
return property;
}
}
但是原始类上的属性似乎总是占优:
public static void Serialize()
{
string serialized = JsonConvert.SerializeObject(
new CannotModify { Keep = 1, Ignore = 2 },
new JsonSerializerSettings { ContractResolver = new JsonIgnoreAttributeIgnorerContractResolver() });
// Actual: {"Keep":1}
// Desired: {"Keep":1,"Ignore":2}
}
我进一步调查后发现了一个名为IAttributeProvider
的接口,可以进行设置(Ignore
属性的值为"Ignore",这是一个需要更改的线索):
...
property.ShouldSerialize = _ => true;
property.AttributeProvider = new IgnoreAllAttributesProvider();
...
public class IgnoreAllAttributesProvider : IAttributeProvider
{
public IList<Attribute> GetAttributes(bool inherit)
{
throw new NotImplementedException();
}
public IList<Attribute> GetAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
}
但代码从未被执行。