[英]How to create a custom deserializer in Jackson for a List containing 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
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.