尝试解决子类型Jackson ION反序列化时,即使在注册子类型之后也缺少类型ID

时间:2018-10-05 19:18:31

标签: java jackson

我有一个界面-

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
interface Base { ... }

我有两个派生类-ClassAClassB。我正在尝试将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中注册子类型。我在基本界面中也有类型的注释。我在这里想念什么?

1 个答案:

答案 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时不起作用。