【发布时间】:2021-01-20 16:55:33
【问题描述】:
我设法在我的活动中进行 API 调用,它确实在 logcat 中向我显示 API 结果,但我不知道如何在我的视图中显示这些数据?
Sample data
注意:数据在data数组下。
{
"data": [
{
"id": "0ade1bfb-6d02-4a1f-9cd4-dc88fa8aadbd",
"name": "a",
"photo": null
},
{
"id": "30a18b38-c563-4b3a-8c7d-af483c616e49",
"name": "b",
"photo": null
},
{
"id": "709804f8-e429-4c9d-b5cd-2cf3b2add98c",
"name": "c",
"photo": null
},
{
"id": "be204e7b-f1ab-45bc-a842-3d5f3f033381",
"name": "d",
"photo": null
},
{
"id": "cafd632d-d9ba-4617-8823-abc145a95e9c",
"name": "e",
"photo": null
}
],
"message": "Data are ready."
}
Activity
private val client = OkHttpClient()
override fun onCreate(savedInstanceState: Bundle?) {
//....
run("api_link")
}
fun run(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {
Log.d("results: ", response.body()!!.string()) // does return the data
// returning data in view?
}
})
}
Question
- 如何定义显示返回数据的元素?
- 如何循环这些数据? (如果返回的数据是对象呢?比如通过 id 获取帖子)
更新
我对我的代码进行了一些更改,现在我收到了org.json.JSONException: No value for services
code
fun run(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {}
override fun onResponse(call: Call, response: Response) {
// added this part
val list: ArrayList<Service> = ArrayList()
getServices(response.body()!!.string(), list)
//
Log.d("results: ", response.body()!!.string())
// Getting view element
val textView: TextView = findViewById(R.id.recycler)
textView.text = list.toString()
}
})
}
fun getServices(response: String, list: ArrayList<Service>) { //service class
var jsonObject = JSONObject(response)
val jsonArray = jsonObject.getJSONArray("services")
for (i in 0 until jsonArray.length()) {
val jsonObject1 = jsonArray.getJSONObject(i)
var listingObject = Service( //service class
jsonObject1.getInt("id"),
jsonObject1.getString("name"),
jsonObject1.getString("image")
)
list.add(listingObject)
}
}
然后我添加了如下服务类:
class Service ( val id: Int, val name: String?, val image: String?) {
}
有什么想法吗?
【问题讨论】:
-
@a_local_nobody 我不这么认为,不
-
@mafortis 尝试在解析更简单的地方使用改造
-
@rcs 我也安装了它,但从未提出过请求,所以我不知道该怎么做?
-
官方文档是从square.github.io/retrofit开始的好地方