Kotlin Retrofit解析报错:预期BEGIN_ARRAY却得BEGIN_OBJECT如何修复
修复「expected BEGIN_ARRAY but was BEGIN_OBJECT」错误
错误原因
你定义的接口返回类型是List<NewsEverything>,期望接口返回JSON数组,但实际接口返回的是包含数组的JSON对象,Gson解析时类型不匹配就会抛出这个错误。
修复步骤
确认接口实际返回的JSON结构
通常新闻类API的返回结构类似这样(以你接口的实际返回为准):{ "status": "ok", "totalResults": 20, "articles": [ { "name": "示例来源", "title": "示例标题", // 其他对应NewsEverything的字段 } ] }新增外层数据类
针对外层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修改API接口的返回类型
把接口的返回类型从Response<List<NewsEverything>>改成Response<NewsEverythingResponse>:interface EverythingAPI { @GET("***") suspend fun getEverything() : Response<NewsEverythingResponse> }调整数据加载逻辑
从返回的外层对象中取出数组列表,再赋值给适配器: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
相关产品推荐
相关产品推荐

