Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
Zowye Avatar asked Oct 24 '25 23:10

Zowye


2 Answers

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>
    )
like image 68
Enzo Lizama Avatar answered Oct 27 '25 13:10

Enzo Lizama


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?
    )
like image 41
Borislav Kamenov Avatar answered Oct 27 '25 15:10

Borislav Kamenov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!