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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- objective-c – Ctrl – 从按钮拖动到方法不起作
- c# – 任务并行库中的任务如何影响ActivityID?
- c# – 线程成本 – 线程增加速度时的最短执行时间
- ios – 如何在Google地图Xcode上显示子视图或按钮
- .net – 当属性已被声明为父元素的属性时,使用XP
- 如何编写正则表达式以匹配标题案例句子(例如:我
- c# – 在我的BIOS设置中没有启用Hyper-V的选项
- 关于 Unable to locate xxx NamespaceHandler fo
- 将AIR应用程序中的SQLite数据库编码更改为UTF-8
- ruby-on-rails – heroku未定义的方法为空?当我
热点阅读