忽略序列化/反序列化的[JsonIgnore]属性 [英] Ignore [JsonIgnore] Attribute on Serialization / Deserialization

查看:199
本文介绍了忽略序列化/反序列化的[JsonIgnore]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有权限修改/扩展的类上,是否可以忽略Json.NET的 [JsonIgnore] 属性?

Is there a way I can ignore Json.NET's [JsonIgnore] attribute on a class that I don't have permission to modify/extend?

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 类,并覆盖看起来是相关方法的东西:

I need all properties in this class to be serialized/deserialized. I've tried subclassing Json.NET's DefaultContractResolver class and overriding what looks to be the relevant method:

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;
    }
}

但是原始类的属性似乎总是​​赢:

but the attribute on the original class seems to always win:

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",因此这是一个提示这可能需要更改):

I dug deeper, and found an interface called IAttributeProvider that can be set (it had a value of "Ignore" for the Ignore property, so that was a clue this might be something that needs changing):

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

但是代码从未被使用过.

But the code isn't ever hit.

推荐答案

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

You were on the right track, you only missed the property.Ignored serialization option.

将合同更改为以下

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;
    }
}

这篇关于忽略序列化/反序列化的[JsonIgnore]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆