【问题标题】:How to parse JSON arrays with retrofit2?如何用retrofit2解析JSON数组?
【发布时间】:2022-01-04 21:53:19
【问题描述】:

这是我的 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, then features.id:2?”我在任何地方都没有找到答案。

我的数据类:

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

API:

interface ApiService {

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

}

链接:https://releases-f89f5.firebaseio.com/.json

【问题讨论】:

  • 应该suspend fun getFeatures() : List&lt;Feature&gt;

标签: android kotlin retrofit2


【解决方案1】:

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

类点:

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

类特征:

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

类 StackOverflow:

data class StackOverflow(
    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}]}]}", 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)}")
         }
     }
}

【讨论】:

  • 谢谢,这很有帮助。
猜你喜欢
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 2019-10-16
  • 2023-04-07
相关资源
最近更新 更多