在Kotlin中使用改造不会出现OnSuccess响应

时间:2018-10-12 12:08:02

标签: android kotlin retrofit2

我是科特林的新朋友。我试图在改造的帮助下调用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?) {

        }

       })

1 个答案:

答案 0 :(得分:1)

更改界面DataApi,如下所示:

interface DataApi {
    @GET("dbnjg")
    fun getDataList(): Call<DataValue>
}

并像这样调用您的api:

 apiInterface.getDataList().enqueue(object : Callback<DataValue> { 
    override fun onResponse(call: Call<DataValue>?, response:Response<DataValue>?) {
        Toast.makeText(baseContext, ""+response?.body()!!, Toast.LENGTH_LONG).show()
        dataValue = response?.body()!!
        val includedList=dataValue.included
    }

    override fun onFailure(call: Call<DataValue>?, t: Throwable?) {

    }

   })