忽略序列化/反序列化的[JsonIgnore]属性

时间:2016-06-21 20:52:52

标签: c# json.net

有没有办法可以忽略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属性,所以这是一个线索可能是需要改变的事情):

...
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();
    }
}

但是代码还没有被击中。

1 个答案:

答案 0 :(得分:15)

您走在正确的轨道上,您只错过了property.Ignored序列化选项。

将您的合同更改为以下

public class JsonIgnoreAttributeIgnorerContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        property.Ignored = false; // Here is the magic
        return property;
    }
}