【问题标题】:How can correctly parse nested JSON Object using Retrofit 2.0 (Kotlin)?如何使用 Retrofit 2.0 (Kotlin) 正确解析嵌套的 JSON 对象?
【发布时间】:2019-07-30 18:24:51
【问题描述】:

以下 JSON 对象是我从服务器接收到的(获取请求)。我需要获取坐标值(纬度、经度)

{
    "loc": {
        "type": "Point",
        "coordinates": [
            -47.0487786,
            -22.9001656
        ]
    },
    "city": "New Jersey",
    "name": "John Doe",
    "_id": "5c7958b3e3234b3472d9917d"
}

我正在尝试使用以下 Poko (Kotlin):

package com.zowye.API.Models

import com.google.gson.annotations.SerializedName


class Salao
    (
    @SerializedName("loc") var coordinate:  , // not sure about the type
    var city: String?,
    var name: String?
)

如何解析它? 谢谢。

【问题讨论】:

  • 您尝试过使用 Gson 吗?它是一个流行的库,可用于自动将 json 映射到数据模型。

标签: android json kotlin retrofit pojo


【解决方案1】:

再添加一个代表被测对象类型的类Location。

    package com.zowye.API.Models

    import com.google.gson.annotations.SerializedName


    class Location (
        var type: String?,
        var coordinates: Float[]?
    )

    class Salao
        (
        @SerializedName("loc") var coordinate: Location,
        var city: String?,
        var name: String?
    )

【讨论】:

    【解决方案2】:

    你应该为“loc”创建一个数据类

    data class Salao(
            @SerializedName("loc")
            val location : Location,
            val city : String,
            val name : String,
            @SerializedName("_id")
            val id : String
        )
    
    data class Location (
            val type : String,
            val coordinates : Array<Float>
        )
    

    【讨论】:

    • 成功了!谢谢我的朋友!
    猜你喜欢
    • 2016-01-01
    • 1970-01-01
    • 2021-02-03
    • 2015-09-12
    • 2018-05-31
    • 1970-01-01
    • 2018-07-12
    • 2021-05-19
    相关资源
    最近更新 更多