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

我正在 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;

    }

    .

    .

    .

食谱服务类:


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


}


函数式编程
浏览 103回答 1
1回答

慕工程0101907

如果 API 响应正是您发布的内容,则响应为无效的 JSON 格式。您可以通过jsonlint检查您的 JSON 有效性。其次,你的错误说,Expected&nbsp;BEGIN_ARRAY&nbsp;but&nbsp;was&nbsp;BEGIN_OBJECT&nbsp;at&nbsp;line&nbsp;1&nbsp;column&nbsp;2&nbsp;path&nbsp;$这意味着,POJO 是为 JSON 数组设计的,但您从 API 中获取的是 JSON 对象。解决方案非常简单。Android Studio 中有大量这样的插件,或者使用这个在线转换器工具。然后希望你不会得到同样的错误,
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java