【发布时间】:2019-03-17 16:00:35
【问题描述】:
我是 Kotlin 的新手。我正在尝试在改造的帮助下调用 API,并且 URL 向我发送了响应,但是我在 response.body() 中做错了什么?价值没有到来。
我的 JSON 响应:-
{
"data": {
"type": "accounts"
"attributes": {
"payment-type": "prepaid"
}
},
"included": [
{
"type": "a"
"attributes": {
"msn": "0468874507"
}
},
{
"type": "b"
"attributes": {
"msn": "38593"
}
}
]
}
在 DataApi.kt 中
interface DataApi {
@GET("dbnjg")
fun getDataList(): Call<ArrayList<DataValue>>
}
在 DataValue.kt 中
class DataValue {
@SerializedName("data")
var data: Data? = null
@SerializedName("included")
val included: ArrayList<DataInclude>? = null
}
在 ApiClient.kt 中
fun getApiClient(): Retrofit? {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
}
return retrofit
}
在 MainActivity 我试图获得响应,但我无法获得响应。我在哪里遗漏了什么或犯了错误?
MainActivity.kt
val apiInterface: DataApi = ApiClient().getApiClient()!!.create(DataApi::class.java)
apiInterface.getDataList().enqueue(object : Callback<ArrayList<DataValue>> {
override fun onResponse(call: Call<ArrayList<DataValue>>?, response: Response<ArrayList<DataValue>>?) {
Toast.makeText(baseContext, ""+response?.body()!!, Toast.LENGTH_LONG).show()
dataValue = response?.body()!!
}
override fun onFailure(call: Call<ArrayList<DataValue>>?, t: Throwable?) {
}
})
【问题讨论】:
-
好吧,那你有什么错误吗?
-
您的 json 响应是一个 JSONObject,而在 Call 中您正在传递一个数组列表.....只需在 DataApi 接口中更改为 Call
-
@nik 谢谢它的工作
-
你也可以使用这个插件为kotlin生成responseClass......plugins.jetbrains.com/plugin/…