4
有没有一种方法可以忽略JSON.NET的[JsonIgnore]
属性,我没有修改/扩展的权限?忽略[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
属性的值,所以这是一个线索,这可能是需要改变的东西):
...
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();
}
}
但是代码没有被击中。
不是一个“解决方案”本身,但你可以做镜像模式和序列化。 – Eris