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 的性能优势,又提供了必要的灵活性来处理复杂的继承和多态场景。
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00- QQwen3-Coder-Next2026年2月4日,正式发布的Qwen3-Coder-Next,一款专为编码智能体和本地开发场景设计的开源语言模型。Python00
xw-cli实现国产算力大模型零门槛部署,一键跑通 Qwen、GLM-4.7、Minimax-2.1、DeepSeek-OCR 等模型Go06
PaddleOCR-VL-1.5PaddleOCR-VL-1.5 是 PaddleOCR-VL 的新一代进阶模型,在 OmniDocBench v1.5 上实现了 94.5% 的全新 state-of-the-art 准确率。 为了严格评估模型在真实物理畸变下的鲁棒性——包括扫描伪影、倾斜、扭曲、屏幕拍摄和光照变化——我们提出了 Real5-OmniDocBench 基准测试集。实验结果表明,该增强模型在新构建的基准测试集上达到了 SOTA 性能。此外,我们通过整合印章识别和文本检测识别(text spotting)任务扩展了模型的能力,同时保持 0.9B 的超紧凑 VLM 规模,具备高效率特性。Python00
KuiklyUI基于KMP技术的高性能、全平台开发框架,具备统一代码库、极致易用性和动态灵活性。 Provide a high-performance, full-platform development framework with unified codebase, ultimate ease of use, and dynamic flexibility. 注意:本仓库为Github仓库镜像,PR或Issue请移步至Github发起,感谢支持!Kotlin08
VLOOKVLOOK™ 是优雅好用的 Typora/Markdown 主题包和增强插件。 VLOOK™ is an elegant and practical THEME PACKAGE × ENHANCEMENT PLUGIN for Typora/Markdown.Less00