Search code examples
androidkotlinretrofit2

How to parse JSON arrays with retrofit2?


This is my JSON response:

{
"features":[
{
"id":1,
"points":[
{
"accuracy":2.40000009537,
"latitude":5.163021,
"longitude":-1.601401
},
{
"accuracy":2.22000002861,
"latitude":5.163061,
"longitude":-1.600696
},
{
"accuracy":2.4300000667572,
"latitude":5.162021,
"longitude":-1.599648
}
]
},
{
"id":2,
"points":[
{
"accuracy":2.09999990463257,
"latitude":5.191406,
"longitude":-1.56806
},
{
"accuracy":2.09999990463257,
"latitude":5.191236,
"longitude":-1.567971
}
]
},

How can I differentiate those coords where is "id":1 or "id":2 like "get features.id:1, then features.id:2?" I didn't find the answer anywhere.

My data class:

data class Location(
    val accuracy: String,
    val latitude: String,
    val longitude: String
) 

Api:

interface ApiService {

    @GET("/.json")
    suspend fun getLocations(): List<Location>

}

Link: https://releases-f89f5.firebaseio.com/.json


Solution

  • I'm understanding you want to parse JSON when you encounter a list object and list array in JSON.

    class Point:

    data class Point(
        val accuracy: Double,
        val latitude: Double,
        val longitude: Double
    )
    

    class Feature:

    data class Feature(
        val id: Int,
        val points: List<Point>
    )
    

    class StackOverflow:

    data class StackOverflow(
        val features: List<Feature>
    )
    

    Parse JSON:

    //parse JSON
    val demo = Gson().fromJson("{\"features\":[{\"id\":1,\"points\":[{\"accuracy\":2.40000009537,\"latitude\":5.163021,\"longitude\":-1.601401}]},{\"id\":2,\"points\":[{\"accuracy\":3.69000005722046,\"latitude\":5.190501,\"longitude\":-1.567918}]}]}", StackOverflow::class.java)
    
    // Check 
    demo.features[0].id      // = 1
    demo.features[0].points[0].accuracy // = 2.40000009537
    demo.features.forEach { feature ->
         Log.d("LogDebug", "data feature ${Gson().toJson(feature)}")
         if (feature.id == 2) {
             feature.points.forEach { point ->
             Log.d("LogDebug", "data point ${Gson().toJson(point)}")
             }
         }
    }