com.fasterxml.jackson.databind.exc.InvalidTypeIdException:无法将类型 id '[' 解析为子类型

问题描述 投票:0回答:1

我有一个名为 Fruit 的抽象类,我将

@JsonTypeInfo
@JsonSubTypes
放在其上,如下所示:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "fruits")
@JsonSubTypes({
    @Type(value = Apple.class, name = "sandbox.Apple"),
    @Type(value = FruitGroup.class, name = "sandbox.FruitGroup")
})
public abstract class Fruit {

    public abstract String getName();

    @Override
    public String toString() {
        return "Fruit [getName()=" + getName() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
    }
}

我的派生类看起来像这样

@JsonTypeName("sandbox.Apple")
public class Apple extends Fruit {

    private String _name;

    public void setName(String name) {
        _name = name;
    }

    @Override
    public String getName() {
        return _name;
    }

======[已更新]====== 我还有 FruitGroup 类,它扩展了 Fruit 并包含 Fruit 数组。

@JsonTypeName("sandbox.FruitGroup")
public class FruitGroup extends Fruit {
private Fruit[] _Fruit;
private String _name;
private String _category;

public Fruit[] getFruit() {
    return _Fruit;
}

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

public void setName(String name) {
    _name = name;
}

@Override
public String getName() {
    return _name;
}

public void setCategory(String category) {
    _category = category;
}

public String getCategory() {
    return _category;
}

}

当我尝试将 jsontext 反序列化为 Fruit 对象时,我发现以下异常:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id '[' as a subtype of `sandbox.FruitGroup`: known type ids = [FruitGroup, sandbox.Apple] at [Source: (String)"{"fruits":[["sandbox.Apple",{"name": "Apple"}]],"name": "Fruit Group"}"; line: 1, column: 11]
at com.fasterxml.jackson.databind.exc.InvalidTypeIdException.from(InvalidTypeIdException.java:43)

jsontext [已更新]实际上是由 jackson 版本 2.10.2 生成的,我以前没有在我的类上添加任何 JSON 注释。在我将 jackson 版本升级到 2.11.0 后,我还更新了我的抽象类以将 JSON 注释放入其中。然后我尝试使用 jackson 版本 2.11.0 对其进行反序列化,但出现错误。你们能帮我解决这个问题吗? 这是我的 jsontext

{
    "fruit": [
        [
            "sandbox.Apple",
            {
                "name": "Apple1"
            }
        ]
    ],
    "name": "Group of apples",
    "category": "Sweet fruit"
}
java json jackson jackson-databind
1个回答
0
投票

您的代码失败,因为在您的 json 文件中您有

"fruits": []
,因此您将 fruits 与 json 数组关联,而在您的抽象
Fruit
类中,您期望
"fruits"
属性引用您想要的子类的名称反序列化你的json。所以如果你像下面这样修改你的 json :

{
    "fruits": "sandbox.Apple",
    "name": "MyApple"
}

然后您可以将其反序列化为

Apple
类的
Fruit
子类:

Fruit fruit = mapper.readValue(src, Fruit.class);
System.out.println(fruit); //<-- Apple(_name=MyApple)

因此,您可以决定更改 json 格式以匹配您的 java 类,或者决定更改您的 java 类以匹配您的 json 文件。

© www.soinside.com 2019 - 2024. All rights reserved.