You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit调用NY Times API报错:Expected BEGIN_ARRAY but was BEGIN_OBJECT

问题解决:Expected BEGIN_ARRAY but was BEGIN_OBJECT 错误

错误原因

你的Retrofit接口定义直接返回List<ResponseCategory>,但NY Times API实际返回的是顶层对象(包含status、copyright、num_results、results字段),分类列表嵌套在results数组中。Gson解析时期望顶层是数组,实际收到的是对象,因此抛出该错误。

解决方案

新增一个顶层响应模型类匹配API完整返回结构,再修改接口返回类型即可。

  1. 创建顶层响应模型类
import com.google.gson.annotations.SerializedName

data class CategoriesResponse(
    @SerializedName("status") val status: String,
    @SerializedName("copyright") val copyright: String,
    @SerializedName("num_results") val numResults: Int,
    @SerializedName("results") val categories: List<ResponseCategory>
)
  1. 修改Retrofit接口返回类型
import com.poklad.androidtestprojectny.data.remote.model.CategoriesResponse
import com.poklad.androidtestprojectny.utils.ApiConstants
import retrofit2.http.GET
import retrofit2.http.Query

interface NYTimesApi {
    @GET(ApiConstants.GET_ALL_CATEGORIES)
    suspend fun getAllCategories(
        @Query("api-key") apiKey: String = ApiConstants.API_KEY,
    ): CategoriesResponse
}
  1. 调用接口获取数据
    调用接口后,通过response.categories就能获取到你需要的List<ResponseCategory>列表。

补充说明

你现有的ResponseCategory模型类字段映射完全正确,无需修改,只需新增顶层响应类适配API的完整返回结构即可解决解析错误。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:38:11