How get JSON Object with Retrofit 2 and Android Studio?

大憨熊 提交于 2019-12-25 03:53:53

问题


I am making an application in Android Studio and I want to consume API for cooking recipes, I have the following response from the API that I am consuming with Android Studio and Java:

API Response

  "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,

And continue with more 'recipe', what I want is to get only the array of hits that all the recipes have to be able to show in my application, the problem is that I get the following error:

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

I understand that it is because it expects an array and it obtains a JSON object, but I do not know how to parse it, I have my Recipe model class and the RecipeService service and I manage everything in MainActivity, I have seen in some answers that I would have to do an intermediate response, but I do not understand how I could implement it in my code, then I show the classes that handle all this.

Recipe Class (Model):

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 Class:

    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:


If API response is exactly what you post then the response is INVALID JSON format. You may check your JSON validity by jsonlint.

Secondly, your error says,

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

Which means, POJO is designed for a JSON array, but from the API you are getting a JSON object.

The solution is really simple.

There are tons of plugins in Android Studio like this, or go this online converter tool. Then hopefully you will not get the same error,



来源:https://stackoverflow.com/questions/56723991/how-get-json-object-with-retrofit-2-and-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!