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完整返回结构,再修改接口返回类型即可。
- 创建顶层响应模型类
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> )
- 修改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 }
- 调用接口获取数据
调用接口后,通过response.categories就能获取到你需要的List<ResponseCategory>列表。
补充说明
你现有的ResponseCategory模型类字段映射完全正确,无需修改,只需新增顶层响应类适配API的完整返回结构即可解决解析错误。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

