[英]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.