改装 response.body!! Kotlin android 工作室

retrofit response.body!! Kotlin android studio

我用Kotlin改造遇到问题代码如下:

MainActivity.kt

 val apiInterface = ApiInterface.create().getCountry()
        apiInterface.enqueue( object : Callback<List<data>>{
            override fun onResponse(call: Call<List<data>>?, response: Response<List<data>>?) {
                if(response?.body() != null){
                    val adapter = ArrayAdapter(this@MainActivity,android.R.layout.simple_spinner_item,response.body()!!)

                    binding.spCountry.adapter=adapter //spCountry is a spinner
                }
            }
            override fun onFailure(call: Call<List<data>>?, t: Throwable?) {}
        })

ApiInterface.kt

interface ApiInterface {
    @GET("/v3.1/all")
    fun getCountry() : Call<List<data>>
    companion object {
        var BASE_URL = "https://restcountries.com/v3.1/all/"
        fun create() : ApiInterface {
            val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }
}

data.kt

data class data(
    @SerializedName("name") val name: name
)
data class name(
    @SerializedName("common") val common: String
)

我得到的结果是微调器中的这个,我只想要国家/地区的名称

您可以执行一个简单的 map 操作将您的 List<data> 转换为 List<String>

val originalList: List<data> = // Response from retrofit
val newList: List<String> = originalList.map { it.name.common }

try it yourself