java - GSON IllegalStateException:应为 BEGIN_OBJECT 但为 BEGIN_ARRAY
问题描述
我目前正在使用 Retrofit 来调用这个URL。我正在努力理解如何基于 JSON 映射你的 POJO。这是我的代码:
final ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<Recipe> call = apiInterface.getRecipe();
call.enqueue(new Callback<Recipe>() {
@Override
public void onResponse(Call<Recipe> call, Response<Recipe> response) {
Log.v("SUCCESS", String.valueOf(response.isSuccessful()));
mRecipeListResponse = Collections.singletonList(response.body());
for (Recipe recipe: mRecipeListResponse){
Log.v("RECIPE", recipe.getId());
}
}
@Override
public void onFailure(Call<Recipe> call, Throwable t) {
Log.v("SUCCESS", String.valueOf(t.getMessage()));
}
});
}
public interface ApiInterface{
@GET("topher/2017/May/59121517_baking/baking.json")
Call<Recipe> getRecipe();
}
数据结构/POJO:
public class Recipe {
protected List<Ingredients> ingredients;
private String id;
private String servings;
private String name;
private String image;
private List<Steps> steps;
public List<Ingredients> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
this.ingredients = ingredients;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
@Override
public String toString() {
return "ClassPojo [ingredients = " + ingredients + ", id = " + id + ", servings = " + servings + ", name = " + name + ", image = " + image + ", steps = " + steps + "]";
}
}
错误:
07-21 15:06:00.238 20548-20548/kitchenpal.troychuinard.com.kitchenpal V/SUCCESS: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
编辑:我已经更新了我的 POJO 并且仍然收到相同的错误
解决方案
你应该像这样改变你的模型
public class Recipe {
private List<Ingredients> ingredients;
private String id;
private String servings;
private String name;
private String image;
private List<Steps> steps;
//Your getter and setters
}
推荐阅读
- wordpress - 带有 Timber/Twigg 模板的 WordPress 前端的 TinyMCE
- sql-server - 选择具有不同列值的不同 ID
- python - python的问题:未定义的符号:sqmI
- qemu - U-Boot with OpenSBI on HiFive Unleashed in QEMU: Store/AMO access fault
- javascript - 在 React 应用程序的 Util 文件中初始化 Google 地图
- android-studio - 为什么我没有收到错误并且应用程序无法打开
- sql - 将字符串类型的日期和时间连接到一个 TIMESTAMP 列 [Impala]
- variables - 在 TFS 2018 Release Task 之间传递一个变量,然后在门步骤中使用该变量
- node.js - req.body 始终是一个空对象
- python - 一旦在python中打开一个变量分配给一个文件,当重新分配变量时文件会发生什么?