【问题标题】:Parsing json difficulties解析json困难
【发布时间】:2020-07-06 16:55:39
【问题描述】:

您好,我一直在开发一个食谱应用程序,我一切正常,但在实际的解析函数上没有错误。如果您能给我一些提示,我将不胜感激,因为我是这方面的新手,而且我从一个更简单的 api 链接中学习,而这个更难解析,我不知道该怎么做。

这是我要解析的链接:
https://api.edamam.com/search?q=recipe&app_id=fd6b284e&app_key=d7f2b601ed78fb706f422c0bb83eeb6b

这是代码。基本上在循环过程中,我在“图像”处收到一个错误,它说找不到它。我花了一些时间来理解为什么,因为只有食谱是数组“命中”的一个元素,但“食谱”也是一个包含更多对象的对象,我很好奇是否有办法为食谱做另一个循环但我不知道该怎么做,因为它是一个对象而不是一个实际的数组?我正在尝试在 recyclerviewer 中显示图像、配方名称和成分。而且我认为它不显示任何内容的唯一原因是因为我做错了解析。我尝试在实际的 RV 上放置背景,一旦我启动它就会显示背景,所以我只是假设这可能是实际问题。 (错误的解析)

  private void parseJSON()
    {
        String url = "https://api.edamam.com/search?q=recipe&app_id=fd6b284e&app_key=d7f2b601ed78fb706f422c0bb83eeb6b";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("hits");
                            for (int i=0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(i);
                                String recipeName = hit.getString("recipe");
                                String imageURL = hit.getString("image");
                                String ingredients = hit.getString("ingredients");

                                mMeals.add(new Meals(imageURL, recipeName, ingredients));

                            }

                            mMealAdapter = new MealAdapter(HomeActivity.this, mMeals);
                            mRecyclerView.setAdapter(mMealAdapter);
                            mMealAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);

    }

【问题讨论】:

    标签: json api android-studio parsing


    【解决方案1】:

    recipe 不是字符串,而是对象。您应该调用getJSONObject('recipe') 并在此jsonobject 中找到image

    JSONObject hit = jsonArray.getJSONObject(i);
    JSONObject recipeObject = hit.getJSONObject("recipe");
    String imageURL = recipeObject.getString("image");
    String recipeName = hit.getString("label");
    

    我认为recipeNamerecipeObject 中是label

    ingredients也不是字符串,是JSONObject,使用getJSONObject('ingredients')得到这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多