ASP.NET Core 8 Web API中序列化继承抽象类的多类型列表问题
问题原因
ASP.NET Core 8默认使用的System.Text.Json序列化器不支持隐式多态序列化。当序列化List<BaseClass>时,序列化器只会识别基类BaseClass的成员(而你的基类无任何属性),导致派生类A、B的属性无法被序列化,最终表现为rows看似为空数组。
解决方案
方案1:给基类添加派生类型标记
直接在BaseClass上通过JsonDerivedType特性声明所有可能的派生类,明确告诉序列化器需要识别这些子类:
[JsonDerivedType(typeof(A))] [JsonDerivedType(typeof(B))] public abstract class BaseClass { }
方案2:全局配置Json序列化选项
如果不想修改基类代码,可以在Program.cs中全局配置Json序列化器,添加多态类型映射:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.TypeInfoResolverChain.Insert(0, new DefaultJsonTypeInfoResolver { Modifiers = { typeInfo => { if (typeInfo.Type == typeof(BaseClass)) { typeInfo.PolymorphismOptions = new JsonPolymorphismOptions { DerivedTypes = { new JsonDerivedType(typeof(A)), new JsonDerivedType(typeof(B)) } }; } } } }); });
验证结果
配置完成后,填充测试数据返回:
var table = new Table { PageNumber = 0, PageSize = 20, TotalAmountRecords = 100, TotalAmountPages = 5, RecordOffset = 0, Rows = new List<Row> { new Row { Cells = new List<BaseClass> { new A { PropA = 1 }, new B { PropB = 2 } } } } }; return Ok(table);
会得到正确的JSON输出:
{ "rows": [ { "cells": [ {"PropA":1}, {"PropB":2} ] } ], "pageNumber":0, "pageSize":20, "totalAmountRecords":100, "totalAmountPages":5, "recordOffset":0 }
内容的提问来源于stack exchange,提问作者YaMoef
相关产品推荐
相关产品推荐

