2016-06-21 144 views
4

有没有一种方法可以忽略JSON.NET的[JsonIgnore]属性,我没有修改/扩展的权限?忽略[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属性的值,所以这是一个线索,这可能是需要改变的东西):

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

但是代码没有被击中。

+0

不是一个“解决方案”本身,但你可以做镜像模式和序列化。 – Eris

回答

8

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