如何通过Retrofit 2和Android Studio获取JSON对象?

时间:2019-06-23 12:42:14

标签: java android json retrofit

我正在Android Studio中创建一个应用程序,并且想使用API​​来烹饪食谱,我从使用Android Studio和Java时使用的API得到以下响应:

API响应

  "q" : "pollo",
  "from" : 0,
  "to" : 10,
  "params" : {
    "sane" : [ ],
    "q" : [ "pollo" ],
    "app_id" : [ "02" ],
    "app_key" : [ "\n66b" ]
  },
  "more" : true,
  "count" : 1000,
  "hits" : [ {
    "recipe" : {
      "uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_d56f75c72ab67a45174441af1efe4473",
      "label" : "Pollo con Crema a las Hierbas",
      "image" : "http://cdn.kiwilimon.com/recetaimagen/23127/thumb120x90-15802.jpg",
      "source" : "KiwiLimon",
      "url" : "http://www.kiwilimon.com/receta/carnes-y-aves/pollo-con-crema-a-las-hierbas",
      "shareAs" : "http://www.edamam.com/recipe/pollo-con-crema-a-las-hierbas-d56f75c72ab67a45174441af1efe4473/pollo",
      "yield" : 42.0,

并继续使用更多的“食谱”,我想要的是仅获取所有食谱必须能够在我的应用程序中显示的命中数组,问题是我遇到了以下错误:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我了解这是因为它期望一个数组并获得一个JSON对象,但是我不知道如何解析它,我有我的Recipe模型类和RecipeService服务,而且我在MainActivity中管理所有内容在某些答案中,我将不得不做一个中间响应,但是我不明白如何在代码中实现它,然后展示了处理所有这些问题的类。

配方类别(型号):

public class Recipe {
    private String label;
    private String image;
    private String source;
    private String shareAs;
    private List<String> dietLabels;
    private List<String> healthLabels;
    private List<String> cautions;
    private List<String> ingredientLines;
    private List<String> ingredients;
    private double calories;
    private double totalWeight;
    private List<String> totalNutrients;
    private List<String> totalDaily;

    public String getLabel() {
        return label;
    }
    .
    .
    .

RecipeService类:

    public interface RecipeService {

    String API_ROUTE = "/search";
    String API_KEY = "&app_key=" + Credentials.API_KEY;
    String APP_ID = "&app_id=" + Credentials.APP_ID;
    //String query = "";

    @GET(API_ROUTE)
    Call< List<Recipe> > getRecipe(@Query("q") String q);

}

MainActivity:

 private void getRecipes() {
        Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("https://test-es.edamam.com")
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

        RecipeService recipeService = retrofit.create(RecipeService.class);
        Call<List<Recipe>> call = recipeService.getRecipe("pollo");

        System.out.println("GET RECIPES");
        System.out.println("HEADERS: "+ call.request().headers());

        call.enqueue(new Callback<List<Recipe>>() {
            @Override
            public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {

                System.out.println("RESPONSE CODE: " + response.code());
                for(Recipe recipe : response.body()){

                    System.out.println("AÑADIENDO: " + recipe.getLabel());
                    recipes.add(recipe.getLabel());
                }
                //System.out.println(recipes.toArray().toString());
            }

            @Override
            public void onFailure(Call<List<Recipe>> call, Throwable t) {
                System.out.println("HA OCURRIDO UN FALLO");
                System.out.println(t.getMessage());
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

如果API响应正是您发布的内容,则响应为INVALID JSON格式。您可以通过jsonlint检查JSON有效性。

其次,您的错误提示

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

这意味着POJO是为JSON数组设计的,但是从API中可以获得一个JSON对象。

解决方案非常简单。

Android Studio中有大量的插件,例如this或转到this online converter tool。然后希望您不会遇到相同的错误,