【问题标题】:Get data from certain tag in response (Kotlin, Retrofit)从特定标签获取数据作为响应(Kotlin、Retrofit)
【发布时间】:2021-09-11 14:37:46
【问题描述】:

我正在尝试通过 Retrofit 和 Kotlin 从 Android 应用进行简单的 GET API 调用。

我正在努力从某个响应标签中获取数据。

我正在使用带有分页功能的 Django REST 框架,因此结果包含在标签 results 中。我不知道如何查看这个 results 标签 i.o。改造的整体反应。

我的回答:

{
    "count": 13,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 2,
            "passport_number": 11233546,
            "first_name": "Egor",
            "last_name": "Wexler",
            "email": "string",
            "age": 0,
            "city": "city"
        },
        ...
        { <other customers> },
    ]
}

Customer.kt

import com.google.gson.annotations.SerializedName

data class Customer(
    @SerializedName("passport_number") val passportNumber: Int,
    @SerializedName("first_name") val firstName: String,
    @SerializedName("last_name") val lastName: String,
    @SerializedName("email") val email: String,
    @SerializedName("age") val age: Int,
    @SerializedName("city") val city: String
)

ApiInterface.kt

interface ApiInterface {

    @GET("customers/")
    fun getCustomers() : Call<List<Customer>>

    companion object {

        fun create() : ApiInterface {

            val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }
}

MainActivity.kt

val apiInterface = ApiInterface.create()
apiInterface.getCustomers().enqueue(
    object : Callback<List<Customer>> {
        override fun onResponse(call: Call<List<Customer>>, response: Response<List<Customer>>) {
        // logic for success
        }
        override fun onFailure(call: Call<List<Customer>>, t: Throwable) {
          t.message // java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
        }
    }
)

所以代码最终转到onFailure,并带有我在评论中输入的消息。

如果我在服务器上禁用分页 - 它会按预期工作,因为响应会变成符合应用预期的内容(对象列表 Customer)。

但我希望应用查看标签结果,因为它实际上包含响应。

我觉得这应该是微不足道的,但找不到方法。

对于标有“Expected BEGIN_ARRAY but was BEGIN_OBJECT”的类似问题,我看到了很多答案,但没有一个能解决我的问题。

【问题讨论】:

    标签: android kotlin retrofit2


    【解决方案1】:

    您应该创建一个与您的响应具有相同结构的响应类。

    在你的情况下,这样的事情会做:

    data class PageResult(
       val count: Int,
       val next: Int?,
       val previous: Int?,
       val results: List<Customer>
    )
    

    并在您的 API 接口中使用:

    @GET("customers/")
        fun getCustomers() : Call<PageResult>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多