我得到一个这样的 JSON 对象:
{
"id": "...",
"Nested": {
"nestedId": "..."
}
}
顶层对象中还有许多其他属性Nested
。
我只对顶级对象的十几个字段以及该Nested
对象的感兴趣nestedId
。
此代码将它们放入 Kotlin 数据类中:
import com.fasterxml.jackson.annotation.*
@JsonIgnoreProperties(ignoreUnknown = true)
data class MainObject(
@JsonProperty("id") val id: String,
// ... more properties for other fields
@JsonProperty("nested") val nested: Nested?,
) {
val nestedId: String? get() = nested?.id
}
@JsonIgnoreProperties(ignoreUnknown = true)
data class Nested(
@JsonProperty("id") val id: String
)
我可以用 很好地访问嵌套对象的 id n.nestedId
。
我还是想取消额外的Nested
课程。
我如何使用注释来仅反序列化嵌套的 id 而不是整个对象?
我已经看到了自定义 a JsonDeserializer
,但是它似乎比我的小额外类包含更多的代码和复杂性。
我想我可以使用readTree
和path
,但随后我必须手动映射所有其他字段。
尝试这样的事情
在您的示例中,嵌套(内部)字段是可空的,但如果
nestedId
不可空,那么我建议移出nestedId
构造函数并使其lateinit
: