我有一个界面-
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
interface Base { ... }
我有两个派生类-ClassA
和ClassB
。我正在尝试将Jackson ION序列化和反序列化为基本类型,如下所示-
class TestSerDeSer {
private static ObjectMapper MAPPER = new IonObjectMapper();
static {
MAPPER.registerSubtypes(new NamedType(A.class, "A"));
MAPPER.registerSubtypes(new NamedType(B.class, "B"));
}
public byte[] serialize(Base baseType) {
try {
return MAPPER.writeValueAsBytes(baseType);
} catch (JsonProcessingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public Base deserialize(byte[] bytes) {
Base base;
try {
base = MAPPER.readValue(bytes, Base.class);
return base;
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
我正在创建Class A
的对象,并使用上述函数来序列化和反序列化
Base baseObj = new ClassA(...);
//serialization works fine
byte[] serializedBytes = serialize(baseObj);
//this line throws exception
Base deserializedBase = deserialize(serializedBytes);
例外是-
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class mypackage.path.Base]: missing type id property 'type'
我正在ObjectMapper中注册子类型。我在基本界面中也有类型的注释。我在这里想念什么?
答案 0 :(得分:1)
您的示例使用带有ObjectMapper
的标准JSON,但是当序列化格式通过IonObjectMapper
切换为Ion时,它将失败。使用com.fasterxml.jackson.dataformat:jackson-dataformat-ion:2.9.7
测试了您的示例,但失败,但有相同的异常。
存在一个未解决的问题[avro] Support @JsonSubTypes in schema generation and serialization #11,这意味着并非所有二进制数据格式都支持子类型。打开拉取请求[Ion] Better support for Ion type annotations. #109表示@JsonTypeInfo
在使用Ion时不起作用。