如何使用 retrofit2 解析 JSON 数组?

How to parse JSON arrays with retrofit2?

这是我的 JSON 回复:

{
"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
}
]
},

如何区分“id”:1 或“id”:2 的坐标,例如“get features.id:1,然后 features.id:2?”我在任何地方都找不到答案。

我的数据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

我了解到,当您在 JSON 中遇到列表对象和列表数组时,您想解析 JSON。

class 点数:

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

class 特点:

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

class Whosebug:

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

解析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}]}]}", Whosebug::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)}")
         }
     }
}