繁体   English   中英

处理响应 Kotlin Retrofit

[英]Handle Response Kotlin Retrofit

我是 Kotlin 和 android 开发的新手。 一直在努力让我的 retrofit api 工作。
但是在对 SO 进行一些搜索后找到了一种方法。 我现在得到数据响应,但我不知道如何“分离”它,以便我可以解决它。

这是我的 json 回复:

"data": [
    {
        "alpha2Code": "PT",
        "name": "Portugal",
        "prefixCode": null,
        "id": "9ba94c99-7362-47c2-f31f-08d87a662921",
        "active": true,
        "created": "2020-10-27T10:50:46.895831"
    }

和我的 model class

data class Country (
    @SerializedName("alpha2Code")
    val alpha2Code: String?,
    @SerializedName("name")
    val name: String?,
    @SerializedName("id")
    val id: String?,
    @SerializedName("active")
    val active: Boolean,
    @SerializedName("created")
    val created: String?
): Serializable


class Countrys {
    var countrys: List<Country> = emptyList()
}

最后我得到数据 function

fun getDataCountry() {
    val call: Call<Countrys> = ApiClient.getClient.getCountries()

    call.enqueue(object : Callback<Countrys> {
        override fun onResponse(call: Call<Countrys>?, response: Response<Countrys>?) {
            // val carResponse = response.body()
            val body = response?.body()
            Log.e("dadosApi2","retorno response: " + body)
        }

        override fun onFailure(call: Call<Countrys>?, t: Throwable) {
            Log.e("dadosApiError","erro no retorno " + t.message)
        }
    })
}

我收到了回复,但我不知道如何展开数据,例如,我可以将所有国家/地区名称添加到ArrayList中。

我曾尝试在没有 class 国家/地区的情况下使用 <List> 或 Arraylist 进行此操作,但我的回复出现错误:

E/dadosApiError: erro no retorno 预期 BEGIN_ARRAY 但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

fun getDataCountry() {
    val call: Call<ArrayList<Country>> = ApiClient.getClient.getCountries()
    call.enqueue(object : Callback<ArrayList<Country>> {

        override fun onResponse(call: Call<ArrayList<Country>>?, response: Response<ArrayList<Country>>?) {
            // val carResponse = response.body()
            val body = response?.body()

            Log.e("dadosApi2","retorno response: " + body)

        }

        override fun onFailure(call: Call<ArrayList<Country>>?, t: Throwable) {
            Log.e("dadosApiError","erro no retorno " + t.message)
        }

    })
}

我以前也尝试过使用 List

您需要将Countrys class 更改为data class并为countrys这样的国家/地区添加SerializedName data

data class Countrys(@SerializedName("data")var countrys: List<Country>)

然后您可以使用此访问您的数据

var countryNames = mutableListOf<String>()
for (country in response?.body().countrys){
  countryNames.add(country.name)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM