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

Jackson升级2.11.0反序列化旧JSON报InvalidTypeIdException如何解决

问题根因
  • 你当前@JsonTypeInfo配置的多态类型嵌入方式和现有JSON格式不匹配:
    未加注解时Jackson 2.10.2默认多态序列化采用WRAPPER_ARRAY模式,会把类型ID和对象内容包装为二元数组(也就是你JSON里["sandbox.Apple", {"name": "Apple1"}]的格式);但你新增的注解里指定了include = JsonTypeInfo.As.PROPERTY,要求类型ID作为对象的一个独立属性存在,Jackson解析时误把数组开头的[识别为类型ID,直接抛出类型不匹配异常。
  • 额外隐藏问题:FruitGroup类的 getter/setter 命名不匹配,getFruit()对应setFruits(),Jackson无法正确映射fruit字段,会导致反序列化后Fruit数组为空。
解决方案(二选一即可)

方案1:兼容旧JSON数据,修改注解配置

将@JsonTypeInfo的include属性改为WRAPPER_ARRAY,适配现有JSON的数组包装格式,同时统一FruitGroup的getter/setter命名:

  1. 修改Fruit抽象类的注解:
// 删掉property属性,WRAPPER_ARRAY模式下不需要指定属性名
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_ARRAY)
@JsonSubTypes({
    @Type(value = Apple.class, name = "sandbox.Apple"),
    @Type(value = FruitGroup.class, name = "sandbox.FruitGroup")
})
public abstract class Fruit {
    // 原有代码不变
}
  1. 修正FruitGroup的getter/setter命名:
// 把getFruit改为getFruits,和setFruits对应
public Fruit[] getFruits() {
    return _Fruit;
}

public void setFruits(Fruit[] fruits) {
    _Fruit = fruits;
}

方案2:保持PROPERTY嵌入模式,调整JSON格式

如果不需要兼容旧数据,就把JSON里的二元数组结构替换为带类型属性的对象结构,示例如下:

{
    "fruit": [
        {
            "fruits": "sandbox.Apple",
            "name": "Apple1"
        }
    ],
    "name": "Group of apples",
    "category": "Sweet fruit"
}
额外注意事项

你抛出的异常中已知类型ID列表没有sandbox.FruitGroup,如果修改后仍提示类型不存在,可以删掉FruitGroup上的@JsonTypeName注解,直接以@JsonSubTypes中配置的name为准,避免注解扫描不生效的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:09:01