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 的性能优势,又提供了必要的灵活性来处理复杂的继承和多态场景。
kernelopenEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。C0105
baihu-dataset异构数据集“白虎”正式开源——首批开放10w+条真实机器人动作数据,构建具身智能标准化训练基座。00
mindquantumMindQuantum is a general software library supporting the development of applications for quantum computation.Python059
PaddleOCR-VLPaddleOCR-VL 是一款顶尖且资源高效的文档解析专用模型。其核心组件为 PaddleOCR-VL-0.9B,这是一款精简却功能强大的视觉语言模型(VLM)。该模型融合了 NaViT 风格的动态分辨率视觉编码器与 ERNIE-4.5-0.3B 语言模型,可实现精准的元素识别。Python00
GLM-4.7GLM-4.7上线并开源。新版本面向Coding场景强化了编码能力、长程任务规划与工具协同,并在多项主流公开基准测试中取得开源模型中的领先表现。 目前,GLM-4.7已通过BigModel.cn提供API,并在z.ai全栈开发模式中上线Skills模块,支持多模态任务的统一规划与协作。Jinja00
AgentCPM-Explore没有万亿参数的算力堆砌,没有百万级数据的暴力灌入,清华大学自然语言处理实验室、中国人民大学、面壁智能与 OpenBMB 开源社区联合研发的 AgentCPM-Explore 智能体模型基于仅 4B 参数的模型,在深度探索类任务上取得同尺寸模型 SOTA、越级赶上甚至超越 8B 级 SOTA 模型、比肩部分 30B 级以上和闭源大模型的效果,真正让大模型的长程任务处理能力有望部署于端侧。Jinja00