如何使用Retrofit 2和Android Studio获取JSON对象? [英] How get JSON Object with Retrofit 2 and Android Studio?

查看:256
本文介绍了如何使用Retrofit 2和Android Studio获取JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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响应

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

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

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.

食谱类(型号):

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

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:

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());
            }
        });
    }

推荐答案

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

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

其次,您的错误提示

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

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

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

解决方案非常简单.

Android Studio中有大量的插件,例如,或者转到此在线转换器工具.然后希望您不会遇到相同的错误,

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,

这篇关于如何使用Retrofit 2和Android Studio获取JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆