ASP.NET Boilerplate 中 System.Text.Json 处理继承类型的解决方案
问题背景
在 ASP.NET Boilerplate 项目中,当开发者从 Newtonsoft.Json 迁移到 System.Text.Json 时,可能会遇到一个常见问题:JSON 序列化无法正确处理接口继承和多态类型。具体表现为,当返回包含接口类型集合的 DTO 时,System.Text.Json 默认只会序列化接口定义的属性,而忽略了实现类的特有属性。
问题重现
考虑以下数据模型结构:
public class TestResutDto : EntityDto
{
public DateTime TestDate { get; set; }
public IEnumerable<ISubItem> SubItems { get; set; }
}
public interface ISubItem
{
int Prop1 { get; set; }
bool Prop2 { get; set; }
}
public class SubItemModel1 : ISubItem
{
public int Prop1 { get; set; }
public bool Prop2 { get; set; }
public int PropModel1Prop1 { get; set; }
public bool PropModel1Prop2 { get; set; }
}
public class SubItemModel2 : ISubItem
{
public int Prop1 { get; set; }
public bool Prop2 { get; set; }
public int PropModel2Prop1 { get; set; }
public bool PropModel2Prop2 { get; set; }
}
使用 System.Text.Json 时,返回的 JSON 结果会丢失实现类的特有属性,而 Newtonsoft.Json 则能正确序列化所有属性。
原因分析
System.Text.Json 在设计上更加注重性能和安全性,因此在默认情况下不支持多态序列化。这与 Newtonsoft.Json 的行为不同,后者会自动处理继承和多态场景。
解决方案
为了解决这个问题,我们需要为 System.Text.Json 实现一个自定义的多态转换器(PolymorphicConverter)。这个转换器能够识别接口类型,并在序列化时正确处理其具体实现类的所有属性。
实现多态转换器
public class PolymorphicConverter<T> : JsonConverter<T>
{
public override bool CanConvert(Type typeToConvert)
{
return typeof(T).IsAssignableFrom(typeToConvert);
}
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException("Deserialization is not implemented for polymorphic types.");
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
if (value == null)
{
writer.WriteNullValue();
return;
}
var actualType = value.GetType();
var runtimeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = options.PropertyNamingPolicy,
DefaultIgnoreCondition = options.DefaultIgnoreCondition
};
foreach (var converter in options.Converters)
{
if (converter.GetType() != typeof(PolymorphicConverter<T>))
{
runtimeOptions.Converters.Add(converter);
}
}
JsonSerializer.Serialize(writer, value, actualType, runtimeOptions);
}
}
配置使用转换器
在 ASP.NET Core 的 Startup 类中配置 JsonOptions 时,添加这个自定义转换器:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
// 添加其他必要的转换器...
options.JsonSerializerOptions.Converters.Add(new PolymorphicConverter<ISubItem>());
});
技术原理
这个解决方案的核心在于:
-
运行时类型识别:通过
value.GetType()获取对象实际的运行时类型,而不是使用编译时类型。 -
选项继承:创建新的 JsonSerializerOptions 实例,继承父选项的命名策略和忽略条件,确保序列化行为一致。
-
转换器过滤:复制其他转换器到新选项中,但排除当前的多态转换器,避免无限递归。
-
类型特定序列化:使用
JsonSerializer.Serialize的重载版本,显式指定实际类型进行序列化。
注意事项
-
反序列化限制:当前实现仅支持序列化,反序列化需要额外实现。
-
性能考虑:每次序列化创建新的 JsonSerializerOptions 实例会有轻微性能开销,但对于大多数应用场景可以接受。
-
复杂类型处理:如果继承体系中有更复杂的场景,可能需要进一步扩展转换器逻辑。
结论
通过实现自定义的 PolymorphicConverter,我们可以在 ASP.NET Boilerplate 项目中使 System.Text.Json 达到与 Newtonsoft.Json 相似的多态序列化行为。这种解决方案既保持了 System.Text.Json 的性能优势,又提供了必要的灵活性来处理复杂的继承和多态场景。
GLM-5智谱 AI 正式发布 GLM-5,旨在应对复杂系统工程和长时域智能体任务。Jinja00
GLM-5-w4a8GLM-5-w4a8基于混合专家架构,专为复杂系统工程与长周期智能体任务设计。支持单/多节点部署,适配Atlas 800T A3,采用w4a8量化技术,结合vLLM推理优化,高效平衡性能与精度,助力智能应用开发Jinja00
jiuwenclawJiuwenClaw 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。Python0194- QQwen3.5-397B-A17BQwen3.5 实现了重大飞跃,整合了多模态学习、架构效率、强化学习规模以及全球可访问性等方面的突破性进展,旨在为开发者和企业赋予前所未有的能力与效率。Jinja00
AtomGit城市坐标计划AtomGit 城市坐标计划开启!让开源有坐标,让城市有星火。致力于与城市合伙人共同构建并长期运营一个健康、活跃的本地开发者生态。01
awesome-zig一个关于 Zig 优秀库及资源的协作列表。Makefile00