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
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:
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)using following code
Also, note that creating
objectMapper
is an expensive operation so you don’t want to do it for each deserialization