Newtonsoft 特性[JsonIgnore ] 对于继承属性的神奇效果
阅读前请有点基础
[JsonIgnore] public DateTime CreateTimccc { get; set; }
一般用Newtonsoft 序列化类时候,如果不要序列化这个属性,在上面加这个特性就好了(ps.这个特性和Newtonsoft和Text.Json的名称重复,注意不要搞错)
定义子类和父类,用隐藏基类属性的方式
class CommonRelationTest : CommonRelationba { public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { public int RelationBusinessState { get; set; } = 1; }
测试代码
Console.WriteLine(JsonConvert.SerializeObject(new CommonRelationTest())); Console.WriteLine(JsonConvert.SerializeObject(new CommonRelationba()));
结果如下
接下来,代码修改一下,加入[JsonIgnore]特性
class CommonRelationTest : CommonRelationba { public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { [JsonIgnore] public int RelationBusinessState { get; set; } = 1; }
class CommonRelationTest : CommonRelationba { [JsonIgnore] public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { public int RelationBusinessState { get; set; } = 1; }
代码,很神奇吧,好像和预期的不一样,预期上面应该是输出 {} ,再改一下
class CommonRelationTest : CommonRelationba { [JsonIgnore] public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { [JsonIgnore] public int RelationBusinessState { get; set; } = 1; }
这个原因是 JsonIgnore attribute on shadowed properties · Issue #463 · JamesNK/Newtonsoft.Json (github.com) 里面有解释
主要就是要区分new属性和原本,不然会降低灵活性,如果正好有人需要序列化基类的属性呢?(需求就是这样,我就不要评判)
如果要实现想要的需求,可以通过虚方法去实现
如果你虚方法用这种写法,那么结果是
class CommonRelationTest : CommonRelationba { [JsonIgnore] public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { public virtual int RelationBusinessState { get; set; } = 1; }
class CommonRelationTest : CommonRelationba { public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { [JsonIgnore] public virtual int RelationBusinessState { get; set; } = 1; }
接下来写下真的虚方法
class CommonRelationTest : CommonRelationba { public override int RelationBusinessState { get; set; } = 2; } class CommonRelationba { [JsonIgnore] public virtual int RelationBusinessState { get; set; } = 1; }
class CommonRelationTest : CommonRelationba { [JsonIgnore] public override int RelationBusinessState { get; set; } = 2; } class CommonRelationba { public virtual int RelationBusinessState { get; set; } = 1; }
class CommonRelationTest : CommonRelationba { [JsonIgnore] public override int RelationBusinessState { get; set; } = 2; } class CommonRelationba { [JsonIgnore] public virtual int RelationBusinessState { get; set; } = 1; }
注意对比下不同, 果然,代码很神奇哦,
我理解是对于new的属性newtonsoft会先解析本类的属性,如果这个new的属性正好被JsonIgnore,那么newtonsoft 回去找基类的属性(等于是有2个相同名称的属性)
而用虚方法重写,newtonsoft 就不会往基类寻找属性了(等于是只有1个属性)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异