从JSON反序列化多维数组

时间:2018-09-21 23:33:39

标签: json spring-boot kotlin jackson

我需要帮助从JSON字符串反序列化以下矩阵

[[0,241680,1504951,608814],[242011,0,1422310,526173],[1509111,1427078,0,929523],[607952,525919,922264,0]]

问题是我不知道在Kotlin中使用什么数据结构来做到这一点。

有什么想法吗?

到目前为止,我已经尝试了以下方法:

    private fun createMatrix(json: String, mapper: ObjectMapper): List<List<Long>> {
        val typeFactory = mapper.typeFactory
        return mapper.readValue(json, typeFactory.constructCollectionType(List::class.java, IntArray::class.java))
    }

1 个答案:

答案 0 :(得分:1)

Jackson允许您将类型引用指定为更好的非共性对象

val mapper = ObjectMapper()
    .registerModule(KotlinModule())

fun main(args: Array<String>) {
    val list = testList("[[0,241680,1504951,608814],[242011,0,1422310,526173],[1509111,1427078,0,929523],[607952,525919,922264,0]]")
    val array = testArray("[[0,241680,1504951,608814],[242011,0,1422310,526173],[1509111,1427078,0,929523],[607952,525919,922264,0]]")
    println(list)
    println(array)
}

fun testList(text: String): List<List<Int>> {
    return mapper.readValue(text, object : TypeReference<List<List<Int>>>() {} )
}

fun testArray(text: String): Array<Array<Int>> {
    return mapper.readValue(text, object : TypeReference<Array<Array<Int>>>() {} )
}