首页 > 解决方案 > 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 并且仍然收到相同的错误

标签: javaandroidgsonretrofit

解决方案


你应该像这样改变你的模型

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

        }

推荐阅读