如何使用jackson反序列化到Kotlin集合 [英] How to use jackson to deserialize to Kotlin collections
本文介绍了如何使用jackson反序列化到Kotlin集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例代码我想要的:
data class D(val a: String, val b: Int)
val jsonStr = """[{"a": "value1", "b": 1}, {"a": "value2", "b":"2}]"""
// what I need
val listOfD: List<D> = jacksonObjectMapper().whatMethodAndParameter?
推荐答案
使用Jackson Kotlin模块当前版本,如果您导入完整的模块包或特定的扩展功能,您将拥有所有可用的扩展方法。例如:
With Jackson Kotlin Module current versions, if you import the full module package or the specific extension function you'll have all extension methods available. Such as:
import com.fasterxml.jackson.module.kotlin.*
val JSON = jacksonObjectMapper() // keep around and re-use
val myList: List<String> = JSON.readValue("""["a","b","c"]""")
因此,Kotlin的Jackson模块将会推断出正确的类型,你不需要 TypeReference
实例。
Therefore the Jackson Module for Kotlin will infer the the correct type and you do not need a TypeReference
instance.
所以你的情况(稍微重命名并修复了数据类和JSON):
so your case (slightly renamed and fixed the data class, and JSON):
import com.fasterxml.jackson.module.kotlin.readValue
data class MyData(val a: String, val b: Int)
val JSON = jacksonObjectMapper()
val jsonStr = """[{"a": "value1", "b": 1}, {"a": "value2", "b": 2}]"""
val myList: List<MyData> = JSON.readValue(jsonStr)
您还可以使用以下表格:
You can also use the form:
val myList = JSON.readValue<List<MyData>>(jsonStr)
如果没有导入,您将收到错误,因为找不到扩展功能。
Without the import you will have an error because the extension function is not found.
这篇关于如何使用jackson反序列化到Kotlin集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文