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

System.Text.Json多态反序列化异常:$type非首属性时出错

.NET 8中System.Text.Json多态反序列化的顺序依赖问题

在.NET 8环境下,使用System.Text.Json处理多态类型反序列化时存在以下行为:当抽象基类配置了[JsonPolymorphic]和[JsonDerivedType]特性后,调用JsonSerializer.Deserialize<BaseClass>()时,若类型鉴别符$type是JSON对象的首属性,反序列化可正常完成;若$type位于其他属性之后,则会抛出System.NotSupportedException异常。

代码示例

[JsonPolymorphic]
[JsonDerivedType(typeof(DerivedClass), "derived")]
public abstract class BaseClass
{
    public BaseClass() { }
}
public class DerivedClass : BaseClass
{
    public string? Whatever { get; set; }
}

JSON示例

  • 可正常反序列化的JSON:
{"$type": "derived", "whatever": "Bar"}
  • 触发异常的JSON:
{"whatever": "Bar", "$type": "derived"}

异常信息

System.NotSupportedException: 'Deserialization of types without a parameterless constructor...'

结论

这是System.Text.Json的预期设计。

System.Text.Json的多态反序列化逻辑要求类型鉴别符$type必须作为JSON对象的第一个属性出现。这是因为序列化器需要在处理对象的其他属性之前,先通过$type确定要实例化的具体派生类类型。如果$type不在首位置,序列化器会先尝试实例化抽象基类(抽象类本身无法被实例化),进而抛出上述异常——即使基类定义了无参构造函数,此时序列化器还未识别到需要创建派生类实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:48:18