【问题标题】:Parse json map in Retrofit在 Retrofit 中解析 json 映射
【发布时间】:2021-09-30 08:27:50
【问题描述】:

我有像这样返回 json 响应的 Web 服务

"map": [
        [
            0,
            "A mother of our mother"
        ],
        [
            2,
            "A brother of our father"
        ],
        [
            1,
            "A daughter of our sister"
        ]
    ],

我如何定义数据类来处理这个响应?

data class Map(
   @SerializedName("map")
   val map : <What type/class definition here>

)

【问题讨论】:

    标签: android kotlin retrofit2


    【解决方案1】:

    应该是这样的:

    data class Map(
        @SerializedName("map")
        val map : List<Collection<Any>>
    )
    

    我已经能够通过这个测试来解析它:

    @Test
    fun testJson() {
        val myMap = Gson().fromJson(json, Map::class.java)
    
        myMap.map.forEach { it ->
            println(it)
        }
        assert(myMap != null)
    }
    

    记得用 {} 包装您的 json 以进行测试

    【讨论】:

    • 对,我使用@Nitin Jain 解决了这个问题,因为起初我只是对嵌套数组感到困惑。谢谢。
    【解决方案2】:

    此 JSON 表示对象数组。

    data class Map(
      @SerializedName("map")
      val map : List<List<Any?>>
    )
    

    【讨论】:

    • 我用 List> 解决了它,因为默认情况下所有解析为字符串。所以我不必再投了。
    猜你喜欢
    • 2016-06-26
    • 2020-06-16
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 2019-01-19
    • 1970-01-01
    相关资源
    最近更新 更多