处理响应 Kotlin 改造

Handle Response Kotlin Retrofit

我是 Kotlin 和 android 开发的新手。一直在努力让我的改造 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"
    }

和我的模特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()
}

最后是我的获取数据功能

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 个国家/地区的情况下使用 或 Arraylist 来执行此操作,但我的回复出现错误:

E/dadosApiError:错误没有返回预期 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)
}