Kotlin+Android报错:Expected begin_array but was begin_object 求助
问题分析
你遇到的Expected begin_array but was begin_object错误,本质是JSON解析的类型不匹配——你用Gson的fromJson()试图把API返回的数据解析成数组/集合,但PetFinder API返回的根节点是一个JSON对象,不是数组。
解决步骤
- 先明确API返回的真实结构
PetFinder的接口返回一般是这种格式:根节点是对象,真正的宠物列表嵌套在animals字段里:
{ "animals": [ {"id": 1, "name": "Buddy"}, {"id": 2, "name": "Mittens"} ], "pagination": {"count_per_page": 20, "total_count": 100} }
别想着直接解析成List<Animal>,得先套一层根对象。
- 创建对应的实体类
先写根响应类,再写宠物实体类:
public class PetFinderResponse { @SerializedName("animals") private List<Animal> animalList; // 要是需要分页信息,就把pagination字段也加上对应的类 // getter/setter方法 } public class Animal { private int id; private String name; // 其他宠物属性比如breed、age之类的,按需添加 // getter/setter方法 }
- 修正解析代码
不管是直接用Gson解析字符串,还是用Retrofit的Call,都要对应根对象:
- 直接Gson解析:
PetFinderResponse response = new Gson().fromJson(apiResponseString, PetFinderResponse.class); List<Animal> pets = response.getAnimalList();
- Retrofit接口调整:
// 原来错误写法:Call<List<Animal>> getPets(); // 改成: Call<PetFinderResponse> getPets();
然后在enqueue回调里拿数据:
getPetsCall.enqueue(new Callback<PetFinderResponse>() { @Override public void onResponse(Call<PetFinderResponse> call, Response<PetFinderResponse> response) { if (response.isSuccessful() && response.body() != null) { List<Animal> pets = response.body().getAnimalList(); // 这里更新UI即可 } } @Override public void onFailure(Call<PetFinderResponse> call, Throwable t) { // 处理请求失败逻辑 } });
小技巧
直接用Postman调用一次API,把返回的JSON复制下来,用Android Studio的GsonFormat插件一键生成实体类,能避免手动写类时的字段名、类型匹配错误。
内容的提问来源于stack exchange,提问作者Merve Yönetci
相关产品推荐
相关产品推荐

