简体   繁体   中英

How can correctly parse nested JSON Object using Retrofit 2.0 (Kotlin)?

The following JSON object is what I'm receiving from server (get request). I need to get the coordinate values (lat, long)

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

I'm trying do this using the following 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?
)

How can I parse it? Thanks.

Add one more class Location which represents the tested object type.

    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?
    )

You should create a data class for "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>
    )

To build a class for this response, the best answer is:

data class UserAddress(

    @field:SerializedName("loc")
    val loc: Loc? = null,

    @field:SerializedName("city")
    val city: String? = null,

    @field:SerializedName("name")
    val name: String? = null,

     @field:SerializedName("_id")
     val id: String? = null
)

data class Loc(

     @field:SerializedName("coordinates")
     val coordinates: List<Float?>? = null,

     @field:SerializedName("type")
     val type: String? = null
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM