简体   繁体   English

Jackson 反序列化为具体多态 class

[英]Jackson deserialization to concrete polymorphic class

I have following Jackson annotated classes (Kotlin)我有以下 Jackson 注释类(Kotlin)

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes(
    value = [
        JsonSubTypes.Type(value = Child1::class, name = "child1"),
        JsonSubTypes.Type(value = Child2::class, name = "child2")
    ]
)
sealed class Parent 

class Child1: Parent()
class Child2: Parent()

I try to deserialize JSON that does not contain type property but I provide concrete class so it should not matter我尝试反序列化不包含type属性的 JSON 但我提供了具体的 class 所以没关系

// Kotlin extension method provides type in runtime
mapper.readValue<Child1>(json)

I get Missing type id when trying to resolve subtype of... anyway.无论如何Missing type id when trying to resolve subtype of... Is there a way how to tell Jackson to use the type provided in the deserialization and not to try find it from the type property?有没有办法告诉 Jackson 使用反序列化中提供的类型而不是尝试从type属性中找到它?

There's a default implementation class to use for deserialization via defaultImpl :有一个默认实现 class 用于通过defaultImpl进行反序列化:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = Child1.class)

From the Javadoc:来自 Javadoc:

Optional property that can be used to specify default implementation class to use for deserialization if type identifier is either not present, or can not be mapped to a registered type (which can occur for ids, but not when specifying explicit class to use).可选属性,可用于指定默认实现 class 用于反序列化,如果类型标识符不存在,或者无法映射到注册类型(这可能发生在 ids 上,但在指定要使用的显式 class 时不会出现)。 Property has no effect on choice of type id used for serialization;属性对用于序列化的类型 id 的选择没有影响; it is only used in deciding what to do for otherwise unmappable cases.它仅用于决定如何处理其他无法映射的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM