kotlin - 使用 Jackson JsonDeserializer 解码自定义对象
问题描述
我是 Kotlin 的新手(来自 Swift),我有一个非常简单的 json,我需要根据该 json 的字段将其解码为两个不同的 Kotlin 类。如果字段是"type": "Square"
我想解码一个Square
类,如果字段是"type": "Rectangle",
,我想解码一个Rectangle
类。
我需要解码的json是
{
"type": "Square",
"size": "1"
}
或者
{
"type": "Rectangle",
"width": 1,
"length": 2
}
我的 .kt 类就是这样定义的。我写了一个自定义JsonDeserializer
,但它似乎不能作为jp.readValueAs(Square::class.java)
retuns null 工作。
@JsonDeserialize(using = Shape.Deserializer::class)
sealed class Shape {
enum class Type {
Rectangle,
Square
}
abstract val type: Type
data class Square(
val size: Int
) : Shape() {
override val type: Type = Type.Square
}
data class Rectangle(
val width: Int,
val length: Int
) : Shape() {
override val type: Type = Type.Rectangle
}
class Deserializer: JsonDeserializer<Shape>() {
override fun deserialize(jp: JsonParser, ctxt: DeserializationContext?): Shape {
var node = jp.readValueAsTree<JsonNode>()
return when(node.get("type").asText()) {
Type.Square.name ->
jp.readValueAs(Square::class.java)
Type.Rectangle.name ->
jp.readValueAs(Rectangle::class.java)
else -> throw JsonMappingException("")
}
}
}
}
我做错了什么?
干杯
解决方案
回答我自己的问题:我认为可以type
使用我的类上的注释来打开属性Shape
,如下所示
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes(
value = [
JsonSubTypes.Type(value = Shape.Square::class, name = "Square"),
JsonSubTypes.Type(value = Shape.Rectangle::class, name = "Rectangle")
]
)
sealed class Shape {
enum class Type {
Rectangle,
Square
}
abstract val type: Type
data class Square(
val size: Int
) : Shape() {
override val type: Type = Type.Square
}
data class Rectangle(
val width: Int,
val length: Int
) : Shape() {
override val type: Type = Type.Rectangle
}
}
推荐阅读
- xml - 剩余空间过多(bible、xml 和 xsl-fo 到 pdf)
- java - jsonschema2pojo 可以用于在运行时从 json-schema 生成类并从中实例化对象吗?
- rx-java - 使用 TTL 缓存 RxJava 反应值
- excel - 有没有办法复制使用连接公式制作公式的单元格并在另一张表中运行相同的单元格?
- elmish-wpf - 模型视图更新可以与 Uno 平台一起使用吗?
- amazon-web-services - 将 AWS 资源事件添加到 Amazon EventBridge 中的预定义事件
- vue.js - Vue.js - 如何使用 2 for 循环?
- android - Flutter BLE设备后台通信怎么做?
- r - 根据查询字符串值选择要下载的数据集
- swiftui - 如何将短信中的代码正确插入文本字段?