加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:59:43 所属栏目:百科 来源:网络整理
导读:参见英文答案 Can I optionally turn off the JsonIgnore attribute at runtime?3个 有没有办法可以忽略我无权修改/扩展的类的Json.NET的[JsonIgnore]属性? public sealed class CannotModify{ public int Keep { get; set; } // I want to ignore this att
参见英文答案 > Can I optionally turn off the JsonIgnore attribute at runtime?3个
有没有办法可以忽略我无权修改/扩展的类的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();
    }
}

但代码并没有被击中.

解决方法

你是在正确的轨道上,你只错过了属性.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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读