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

Kotlin Retrofit解析报错:预期BEGIN_ARRAY却得BEGIN_OBJECT如何修复

修复「expected BEGIN_ARRAY but was BEGIN_OBJECT」错误

错误原因

你定义的接口返回类型是List<NewsEverything>,期望接口返回JSON数组,但实际接口返回的是包含数组的JSON对象,Gson解析时类型不匹配就会抛出这个错误。

修复步骤

  1. 确认接口实际返回的JSON结构
    通常新闻类API的返回结构类似这样(以你接口的实际返回为准):

    {
      "status": "ok",
      "totalResults": 20,
      "articles": [
        {
          "name": "示例来源",
          "title": "示例标题",
          // 其他对应NewsEverything的字段
        }
      ]
    }
    
  2. 新增外层数据类
    针对外层JSON对象定义对应的数据类,把原来的NewsEverything作为列表字段嵌套进去:

    data class NewsEverythingResponse(
        val status: String,
        val totalResults: Int,
        val articles: List<NewsEverything> // 对应JSON里的数组字段
    )
    

    如果JSON里的数组字段名不是articles,改成实际的字段名即可;如果字段名和Kotlin命名规范不一致,用@SerializedName("字段名")注解映射,比如@SerializedName("total_results") val totalResults: Int

  3. 修改API接口的返回类型
    把接口的返回类型从Response<List<NewsEverything>>改成Response<NewsEverythingResponse>:

    interface EverythingAPI {
        @GET("***")
        suspend fun getEverything() : Response<NewsEverythingResponse>
    }
    
  4. 调整数据加载逻辑
    从返回的外层对象中取出数组列表,再赋值给适配器:

    private fun loadEverythingData(){
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(EverythingAPI::class.java)
    
        job = CoroutineScope(Dispatchers.IO).launch {
            val response = retrofit.getEverything()
    
            withContext(Dispatchers.Main){
                if(response.isSuccessful){
                    response.body()?.let { responseData ->
                        newsEverything = ArrayList(responseData.articles)
                        newsEverything?.let {
                            everythingAdapter = EverythingAdapter(binding.root.context,it)
                            binding.everythingRV.adapter= everythingAdapter
                        }
                    }
                }
            }
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:52:45