忽略[jsonignore]属性序列化 /避难所化



有没有一种方法可以忽略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}
}

i更深入,并找到了一个可以设置的称为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();
    }
}

但是代码永远不会达到。

您在正确的轨道上,您只错过了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;
    }
}

相关内容

  • 没有找到相关文章

最新更新