阅读前请有点基础
[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属性和原本,不然会降低灵活性,如果正好有人需要序列化基类的属性呢?(需求就是这样,我就不要评判)
如果要实现想要的需求,可以通过虚方法去实现
如果你虚方法用这种写法,那么结果是(我这里只展示1个,其余写法和上面输出的结果一样)
class CommonRelationTest : CommonRelationba { [JsonIgnore] public new int RelationBusinessState { get; set; } = 2; } class CommonRelationba { 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; }
注意对比下不同, 果然,代码很神奇哦
标签:Newtonsoft,JsonIgnore,get,int,class,set,CommonRelationba,public,神奇 From: https://www.cnblogs.com/czb071/p/18319217