我正在尝试使用 Jakson 反序列化嵌套的多态类型。这意味着我的顶级类型是指另一种多态类型,最终由非抽象类扩展。这不起作用,它会引发异常。
这是我正在尝试做的一个简化示例。
package com.adfin;
import junit.framework.TestCase;
import org.codehaus.jackson.annotate.JsonSubTypes;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
public class JaksonDouble extends TestCase {
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "name"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = SecondLevel.class, name = "SECOND")
})
public static abstract class FirstLevel {
public abstract String getTestValue();
}
@JsonTypeInfo(
use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "@class"
)
public static abstract class SecondLevel extends FirstLevel {
}
public static class FinalLevel extends SecondLevel {
String test;
@Override public String getTestValue() { return test; }
}
public void testDoubleAbstract() throws IOException {
String testStr = "{ \"name\": \"SECOND\", \"@class\": \"com.adfin.JasksonDouble.FinalLevel\", \"test\": \"foo\"}";
ObjectMapper mapper = new ObjectMapper();
FirstLevel result = mapper.readValue(testStr, FirstLevel.class);
}
}
我得到了关于抽象类型的标准例外。
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.adfin.JaksonDouble$SecondLevel, problem: abstract types can only be instantiated with additional type information at [Source: java.io.StringReader@f2a55aa; line: 1, column: 19]
让我解释一下我的用例。我有一个描述数据工作流程的 Json 文档。我在“一级”有一个抽象类型,描述了对单个值的操作。我派生了一堆实现常见操作的非抽象类(我用@JsonSubTypes 对它们进行了注释)。
我有一个特殊的@JsonSubTypes,称为“CUSTOM”。这是另一个抽象类,代表其他人(在普通 jar 之外)编写的自定义操作,他们可以使用“@class”属性指定完全限定的类名。看起来 Jakson 解析器从不读取第二个 lavel 类上的 @JsonTypeInfo 注释。
我怎样才能使这项工作。或者至少我怎样才能使这个用例起作用。