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

.NET Core 7解析appsettings.json时多态反序列化失效问题

问题原因与解决方案

核心问题

你遇到的问题根源在于:.NET的Configuration配置绑定系统,默认并不使用System.Text.Json的多态反序列化逻辑。你添加的JsonDerivedTypeAttribute只会被JsonSerializer识别,但configuration.GetSection().Get<T>()用的是一套独立的反射绑定机制,它不会读取类型鉴别器($type)来自动实例化派生类,只会创建基类Target的实例并赋值匹配的属性。

两种可行解决方案

方案1:手动读取JSON字符串,用JsonSerializer反序列化

直接提取配置节的原始JSON内容,交给JsonSerializer处理,这样就能利用你已经配置好的多态特性:

var configuration = new ConfigurationBuilder()
                      .AddJsonFile("appsettings.json")
                      .Build();

var testTargetSection = configuration.GetSection("TestTarget");
// 获取配置节的原始JSON字符串
var rawJson = testTargetSection.GetRawJson();
// 用JsonSerializer反序列化,自动识别类型鉴别器
var targetObj = JsonSerializer.Deserialize<Target>(rawJson);

方案2:配置绑定选项,指定使用Json序列化器

.NET 7及以上版本支持配置BinderOptions,让Configuration绑定过程使用JsonConfigurationBinder(基于System.Text.Json),这样就能自动识别JsonDerivedTypeAttribute:

var configuration = new ConfigurationBuilder()
                      .AddJsonFile("appsettings.json")
                      .Build();

var binderOptions = new BinderOptions
{
    // 指定使用Json序列化器进行绑定
    BinderType = typeof(JsonConfigurationBinder)
};

var targetObj = configuration.GetSection("TestTarget").Get<Target>(binderOptions);

验证说明

你之前用JsonSerializer.Serialize/Deserialize能正常工作,是因为这个流程完全依赖System.Text.Json的逻辑,会读取JsonDerivedTypeAttribute中定义的类型鉴别器$type,自动实例化对应的派生类;而Configuration默认的绑定逻辑只是简单的属性映射,不处理多态类型的鉴别逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:23