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

15

有没有办法忽略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();
    }
}

但代码从未被执行。


不算是“解决方案”,但您可以创建一个镜像模型并对其进行序列化。 - Eris
1个回答

32

你走在正确的路上,只是忽略了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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接