更新时间:2023-01-16 08:22:50
With Jackson Kotlin Module 当前版本,如果您导入完整的模块包或特定的扩展功能,您将拥有所有可用的扩展方法.如:
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 Module 将推断出正确的类型,您不需要 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)
您也可以使用表格:
val myList = JSON.readValue<List<MyData>>(jsonStr)
不导入就会报错,因为找不到扩展函数.
Without the import you will have an error because the extension function is not found.