如何在 Jackson 中为包含泛型类型的 List 创建自定义反序列化器?

问题描述

你好,关注这个问题

How to create a custom deserializer in Jackson for a generic type?

我想知道如何采用它来解析

public static class Something {
    public static List<Wrapper<Person>> people;
}

这是我目前所拥有的

internal class WithVisibilityDeserializer :
    JsonDeserializer<WithVisibility<*>>(),ContextualDeserializer {
    private var valueType: JavaType? = null

    @Throws(JsonMappingException::class)
    override fun createContextual(
        ctxt: DeserializationContext,property: BeanProperty
    ): JsonDeserializer<*> {
        val wrapperType = property.type
        val valueType = wrapperType.containedType(0)
        val deserializer = WithVisibilityDeserializer()
        deserializer.valueType = valueType
        return deserializer
    }

    @Throws(IOException::class)
    override fun deserialize(parser: JsonParser,ctxt: DeserializationContext): WithVisibility<*> {
        val value: Any? = ctxt.readValue<Any>(parser,valueType)
        return WithVisibility(
            value = value,visibility = false
        )
    }
}

当我试图反序列化这个时,我得到了一个 NPE

data class ViewSelectionFieldTypes(
    @JacksonXmlElementWrapper(localName = "Types",useWrapping = false)
    @JacksonXmlProperty(localName = "Type")
    val type: List<WithVisibility<String>>
)

解决方法

这里的关键是

al valueType = if (!wrapperType.isCollectionLikeType) {
            wrapperType.containedType(0)
        } else {
            // This is needed because there is a List that contains the WithVisibility (List<WithVisibility<String>>)
            wrapperType.containedType(0).containedType(0)
        }

解决方案:

internal class WithVisibilityDeserializer :
    JsonDeserializer<WithVisibility<*>>(),ContextualDeserializer {
    private var valueType: JavaType? = null

    @Throws(JsonMappingException::class)
    override fun createContextual(
        ctxt: DeserializationContext,property: BeanProperty
    ): JsonDeserializer<*> {
        val wrapperType = property.type
        val valueType = if (!wrapperType.isCollectionLikeType) {
            wrapperType.containedType(0)
        } else {
            // This is needed because there is a List that contains the WithVisibility (List<WithVisibility<String>>)
            wrapperType.containedType(0).containedType(0)
        }
        val deserializer = WithVisibilityDeserializer()
        deserializer.valueType = valueType
        return deserializer
    }

    @Throws(IOException::class)
    override fun deserialize(parser: JsonParser,ctxt: DeserializationContext): WithVisibility<*> {
        val value: Any? = ctxt.readValue<Any>(parser,valueType)
        return WithVisibility(
            value = value,visibility = false
        )
    }
}