【问题标题】:Deserialize Multidimensional Array from JSON从 JSON 反序列化多维数组
【发布时间】:2019-02-26 08:40:34
【问题描述】:

我需要帮助从 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))
    }

【问题讨论】:

    标签: json spring-boot kotlin jackson


    【解决方案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>>>() {} )
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多