Dev*_*abc 4 json jackson kotlin json-deserialization jackson-modules
我有字符串形式的 JSON 内容,我首先想用 Jackson 以编程方式遍历它。然后,当我有感兴趣的节点时,我想反序列化它。
我已使用 mapper.readValue 成功反序列化字符串,但现在我想在 jsonNode 而不是字符串上执行此类操作。
package somepackage
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.treeToValue
fun main() {
val mapper = ObjectMapper().registerModule(KotlinModule())
readValueWorksFine(mapper)
treeToValueFails(mapper)
}
fun treeToValueFails(mapper: ObjectMapper) {
val fullJsonContent = """
[{
"product_id":123,
"Comments":
[{
"comment_id": 23,
"message": "Hello World!"
}]
}]
""".trimIndent()
// Traverse to get the node of interest
val commentsNode: JsonNode = mapper.readTree(fullJsonContent).get(0).get("Comments")
// Deserialize
val comments: List<Comment> = mapper.treeToValue<List<Comment>>(commentsNode)
// The line below fails. (I would have expected the exception to be thrown in the line above instead.
// Exception:
// Exception in thread "main" java.lang.ClassCastException: class
// java.util.LinkedHashMap cannot be cast to class somepackage.Comment (java.util.LinkedHashMap is in module
// java.base of loader 'bootstrap'; somepackage.Comment is in unnamed module of loader 'app')
for (comment: Comment in comments) { // This line fails
println(comment.comment_id)
println(comment.message)
}
}
fun readValueWorksFine(mapper: ObjectMapper) {
val commentsJsonContent = """
[{
"comment_id": 23,
"message": "Hello World!"
}]
""".trimIndent()
val comments1: List<Comment> = mapper.readValue<List<Comment>>(commentsJsonContent)
for (comment in comments1) {
println(comment)
}
}
data class Comment(val comment_id: Long, val message: String)
Run Code Online (Sandbox Code Playgroud)
上面的代码会产生以下异常/输出:
Comment(comment_id=23, message=Hello World!)
Exception in thread "main" java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class somepackage.Comment (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; somepackage.Comment is in unnamed module of loader 'app')
at somepackage.TKt.treeToValueFails(T.kt:39)
at somepackage.TKt.main(T.kt:13)
at somepackage.TKt.main(T.kt)
Run Code Online (Sandbox Code Playgroud)
尽管ObjectMapper.treeToValue是一个带有具体化泛型参数的 Kotlin 内联扩展函数(这意味着泛型在运行时被保留),它还是调用了 JavaObjectMapper.treeToValue(TreeNode, Class<T>)方法。由于类型擦除,传递的值Class<T>将丢失泛型类型的泛型类型信息,例如。List<Comment>
因此treeToValue可用于:
mapper.treeToValue<Comment>(commentNode)
Run Code Online (Sandbox Code Playgroud)
但不适用于:
mapper.treeToValue<List<Comment>>(commentsNode)
Run Code Online (Sandbox Code Playgroud)
另请注意,ObjectMapper包含多个带有@SuppressWarnings注释的方法,这会导致某些问题不会出现在编译时,而是出现在运行时。
这是最好的解决方案。它使用了 Kotlin 扩展函数ObjectMapper.convertValue。
val commentsNode = mapper.readTree(fullJsonContent).get(0).get("Comments")
val comments = mapper.convertValue<List<Comment>>(commentsNode)
Run Code Online (Sandbox Code Playgroud)
该解决方案不使用jackson-module-kotlin扩展函数。
val reader = mapper.readerFor(object : TypeReference<List<Comment>>() {})
val comments: List<Comment> = reader.readValue(commentsNode)
Run Code Online (Sandbox Code Playgroud)
因为treeToValue(Kotlin 扩展函数)确实适用于非泛型类型,所以您可以首先获取 JsonNode 列表形式的节点,然后将每个 JsonNode 映射到 Comment。
但不能简单地 return ,这很麻烦mapper.treeToValue(it),因为这会导致类型推断编译错误。
val commentsNode = mapper.readTree(fullJsonContent).get(0).get("Comments")
val comments = commentsNode.elements().asSequence().toList().map {
val comment: Comment = mapper.treeToValue(it)
comment
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11921 次 |
| 最近记录: |