skip to Main Content

I’m trying to parse a json response in model class.
This is the response.
I’m not able to parse it properlly.

[
    {
        "ranges": [
            {
                "lat": 21.8969425959248,
                "lng": 87.12079044431448
            },
            {
                "lat": 21.896755942991668,
                "lng": 87.12070394307375
            }
        ]
    },
    {
        "ranges": [
            {
                "lat": 21.897269860144323,
                "lng": 87.12018627673388
            },
            {
                "lat": 21.897339854770518,
                "lng": 87.12001327425241
            }
        ]
    }
]

I tried adding the response to this models

data class RangesModel(
    @SerializedName("ranges" ) var ranges : ArrayList<Ranges> = arrayListOf()
)
data class Ranges(
    @SerializedName("lat" ) var lat : Double? = null,
    @SerializedName("lng" ) var lng : Double? = null
)

But was not able to parse it properlly.

2

Answers


  1. How about using ObjectMapper?
    You can read more here: https://www.baeldung.com/jackson-object-mapper-tutorial

    In your case You would probably need to use something like:

    Ranges ranges = objectMapper.readValue(json, Ranges.class); 
    
    Login or Signup to reply.
  2. The reason it’s failing for you is that your JSON actually has the format of List<RangesModel> as it starts and ends with the [] braces. So it’s not an object but a list of objects.

    If you use com.fasterxml.jackson.databind.ObjectMapper you could deserialize them into such simplified model (note that values aren’t nullable anymore so both lat and lng are required)

    data class Ranges(
        @JsonProperty("ranges")
        val ranges: List<Range>
    )
    data class Range(
        val lat: Double,
        val lng: Double
    )
    

    using following code

    val objectMapper = ObjectMapper()
    val deserialized = objectMapper.readerForArrayOf(Ranges::class.java)
        .readValue<Array<Ranges>>(json)
    

    Also, note that creating objectMapper is an expensive operation so you don’t want to do it for each deserialization

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search