You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET 6 API返回IChart列表时如何保留子类属性到JSON?

解决ASP.NET 6 API返回IChart列表丢失子类属性的问题

问题原因

返回单个IChart实例时,System.Text.Json能识别到实际运行时类型(比如LineChart),所以会序列化所有属性;但返回IEnumerable<IChart>列表时,序列化器默认以IChart接口为基准,只序列化接口定义的属性,子类的额外属性会被忽略。

解决方案:配置JSON多态序列化

需要在ASP.NET 6的服务配置中,给System.Text.Json添加多态类型支持,让序列化器能识别IChart的派生类,下面是两种常用实现方法:

方法1:源生成模式(推荐,性能更优)

在Program.cs中配置控制器的JSON选项,并定义序列化上下文指定需要处理的类型:

var builder = WebApplication.CreateBuilder(args);

// 添加控制器并配置JSON序列化
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolverChain.Insert(0, JsonSerializerContext.Default);
    });

// 定义序列化上下文,包含所有需要支持的图表类型
[JsonSerializable(typeof(List<IChart>))]
[JsonSerializable(typeof(LineChart))]
[JsonSerializable(typeof(PieChart))] // 有其他Chart子类时,需同步添加
public partial class JsonSerializerContext : JsonSerializerContext
{
}

var app = builder.Build();

// 其他中间件配置...
app.MapControllers();
app.Run();

方法2:运行时配置多态规则

如果不想用源生成,可直接在运行时配置多态规则:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver
        {
            Modifiers =
            {
                typeInfo =>
                {
                    // 针对IChart接口配置多态
                    if (typeInfo.Type == typeof(IChart))
                    {
                        typeInfo.PolymorphismOptions = new JsonPolymorphismOptions
                        {
                            // 指定派生类及对应的类型鉴别符
                            DerivedTypes =
                            {
                                new JsonDerivedType(typeof(LineChart), nameof(LineChart)),
                                new JsonDerivedType(typeof(PieChart), nameof(PieChart))
                            },
                            // 忽略未识别的类型鉴别符(可选)
                            IgnoreUnrecognizedTypeDiscriminators = true
                        };
                    }
                }
            }
        };
    });

var app = builder.Build();

// 其他中间件配置...
app.MapControllers();
app.Run();

效果验证

配置完成后,调用MakeManyCharts接口时,返回的JSON会包含LineChart的xAxisName、yAxisName等子类属性,和单个实例返回的格式一致。

内容的提问来源于stack exchange,提问作者Arkhana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:50:33