从Newtonsoft迁移到Text.Json:序列化含派生子类的记录失败
问题原因与解决方案
这不是操作错误,是System.Text.Json与Newtonsoft.Json的默认行为差异导致的序列化失败:
核心原因
你的代码中Parent2用new关键字重写了Child属性,但基类Parent1的Child属性是internal get(内部访问权限)且标记了[Obsolete]。
- System.Text.Json默认会遍历所有继承的属性,尝试序列化基类的
Child属性时,因getter是internal权限无法访问,直接抛出异常; - Newtonsoft.Json默认会跳过无法访问的属性,优先处理派生类的同名属性,因此能正常运行。
可行解决方案
方案1:忽略所有过时成员
因为基类的Child和Child1的CSV都标记了[Obsolete],直接配置序列化选项跳过这些属性:
var options = new JsonSerializerOptions { IgnoreObsoleteMembers = true }; var serialized = JsonSerializer.Serialize(parent2Instance, options);
方案2:精准标记忽略基类属性
给基类的过时Child属性添加[JsonIgnore]特性,明确排除序列化:
public record Parent1 { [Obsolete] [JsonIgnore] // 添加此特性 public Child1 Child { internal get; set; } = new(); }
方案3:忽略内部访问权限的成员
如果不需要忽略所有过时成员,仅跳过getter/setter为internal的属性:
var options = new JsonSerializerOptions { IgnoreMembersWithAccessibility = JsonMemberAccessibility.Internal }; var serialized = JsonSerializer.Serialize(parent2Instance, options);
内容的提问来源于stack exchange,提问作者PieterV
相关产品推荐
相关产品推荐

