java - 如何使用 Retrofit 2 和 Android Studio 获取 JSON 对象?

标签 java android json retrofit

我正在 Android Studio 中制作一个应用程序,我想使用 API 来 cooking 食谱,我从使用 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);

}

主要 Activity :

 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 响应正是您发布的内容,则该响应为无效 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 。那么希望您不会遇到同样的错误,

关于java - 如何使用 Retrofit 2 和 Android Studio 获取 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723991/

相关文章:

java - 从 Eclipse 调试 Ant 任务

JavaScript 到 java,数组创建的区别

javascript - 从外部 URL 获取带有嵌套数据的 JSON 并将其以纯文本形式显示在 div 中

java - 使用 Jackson 将 Json 文件映射到 POJO 需要 @JsonProperty

java - 使用 java8 (Streams) 的自定义对象比较列表

java - 统一成本搜索

android - 如何在异步类android上设置超时

java - 导入附加库后 Android Studio gradle 错误 - smack

java - 从其他线程上的类调用 wait()

javascript - 尝试从嵌套 json 访问键和值 - javascript