C#通过基类变量序列化时,为什么派生类属性没输出?
使用基类类型声明变量并传入标准json序列化器(如newtonsoft.json或system.text.json)时,默认行为仅序列化基类中定义的属性,导致派生类的特有属性丢失。这是因为序列化器在编译期基于静态类型确定元数据,无法自动识别运行时的派生类型。要解决这个问题,必须显式配置序列化器以启用多态支持,例如在newtonsoft.json中使用`typenamehandling`或在system.text.json中注册具体的派生类型。

如何使用Newtonsoft.Json解决此问题?
在Newtonsoft.Json中,可以通过设置`TypeNameHandling`属性为`Auto`或`All`来自动包含和还原类型信息,从而确保派生类属性被正确序列化。这种方法会在JSON输出中添加一个`$type`字段,记录对象的实际运行时类型,反序列化时据此恢复完整的派生对象结构。

using System; using Newtonsoft.Json; namespace Demo { public class Animal { public string Name { get; set; } } public class Dog : Animal { public string Breed { get; set; } } class Program { static void Main() { Animal animal = new Dog { Name = "Buddy", Breed = "Golden Retriever" }; var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; string json = JsonConvert.SerializeObject(animal, Formatting.Indented); Console.WriteLine(json); } } }
如何使用System.Text.Json解决此问题?
在System.Text.Json中,由于出于安全考虑默认不支持多态序列化,需要在使用`JsonSerializerOptions`时通过`DerivedTypes`集合显式注册派生类。这样序列化器在遇到基类类型时,会检查已注册的派生类,并在输出中包含类型信息,以便反序列化时能准确还原。

using System; using System.Text.Json; using System.Text.Json.Serialization; namespace Demo { public class Animal { public string Name { get; set; } } [JsonDerivedType(typeof(Dog), typeDiscriminator: "Dog")] public class Dog : Animal { public string Breed { get; set; } } class Program { static void Main() { Animal animal = new Dog { Name = "Buddy", Breed = "Golden Retriever" }; var options = new JsonSerializerOptions { WriteIndented = true, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; // 注意:System.Text.Json的多态支持需要 .NET 6+ 且需配置 DerivedTypes // 此处为简化示例,实际需更复杂配置或使用第三方库如 JsonPolymorphism options.TypeInfoResolver = new PolymorphicTypeResolver(); string json = JsonSerializer.Serialize(animal, options); Console.WriteLine(json); } } }
序列化后的JSON结构中类型标识符的具体作用是什么?
在多态序列化生成的JSON中,类型标识符(如`$type`或自定义的discriminator字段)起到了关键的路由作用。它告诉反序列化器当前JSON数据对应的是哪个具体的派生类。如果没有这个标识符,反序列化器只能创建基类实例,派生类的属性将因无法映射而被忽略或报错。因此,该标识符是连接JSON字符串与具体CLR类型的桥梁,确保了数据在传输和存储过程中的完整性。










