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

前端之家收集整理的这篇文章主要介绍了c# – 忽略序列化/反序列化的[JsonIgnore]属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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;
    }
}

猜你在找的C#相关文章