杰克逊寄存器子类型在科特林不起作用 [英] Jackson registerSubtypes not working in Kotlin
本文介绍了杰克逊寄存器子类型在科特林不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
So I've converted this code into Kotlin
like so:
interface Vehicle {
val name: String
}
class Car @JsonCreator constructor(@JsonProperty("name") override val name: String) : Vehicle
class Truck @JsonCreator constructor(@JsonProperty("name") override val name: String) : Vehicle
class Vehicles @JsonCreator constructor(@JsonProperty("vehicles") var vehicles: List<Vehicle>)
fun main() {
val MAPPER = jacksonObjectMapper()
MAPPER.registerSubtypes(NamedType(Truck::class.java, "Truck"))
MAPPER.registerSubtypes(NamedType(Car::class.java, "Car"))
val vehicles = Vehicles(listOf(Car("Dodge"), Truck("Scania")))
val json = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(vehicles)
println(json)
}
但是输出结果如下:
{
"vehicles" : [ {
"name" : "Dodge"
}, {
"name" : "Scania"
} ]
}
它不包含"@type"
字段,因此反序列化不起作用.
It doesn't contain the "@type"
field, so deserialization doesn't work.
有什么想法要解决吗?
Jackson Kotlin版本:2.9.6
Jackson Kotlin version: 2.9.6
推荐答案
我已经弄清楚了.
万一将来有人遇到此问题,在此特定示例中,Vehicle类将需要使用@JsonTypeInfo进行注释,如下所示:
In case anyone has this issue in the future, in this particular example the Vehicle class would need to be annotated with @JsonTypeInfo like so :
@JsonTypeInfo(use = NAME, include = PROPERTY)
interface Vehicle
这篇关于杰克逊寄存器子类型在科特林不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文