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个属性)
浙公网安备 33010602011771号