【问题标题】:Parse nested Json array in Android using Volley使用 Volley 在 Android 中解析嵌套的 Json 数组
【发布时间】:2018-05-01 13:00:30
【问题描述】:

这是我的 JSON - https://api.edamam.com/search?q=chicken

我试图只获取作为食物名称的“标签”和作为食物照片的“图像”。

这是我下面的代码。

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 jsonObject = jsonArray.getJSONObject(i);
                    String recipe = jsonObject.optString("recipe");
                    String name = jsonObject.optString("label");
                    String label = jsonObject.optString("image");

                    txtDisplay.setText(recipe + name + label);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }



        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", "Error");
        }
    });

    queue.add(obreq);
}

}

此代码返回 JSON 数据,但它返回所有数据。

任何人都可以提供示例代码,以便它只返回特定的值。

谢谢

【问题讨论】:

标签: android json android-volley


【解决方案1】:

这是一个小函数,它只提取需要的内容,即 labelimageList&lt;FoodModel&gt; 对象中,可用于列表视图或回收器视图以显示项目。

 private List<FoodModel> getFoodList(String json) throws JSONException {
    List<FoodModel> foodModels = new ArrayList<>();
    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("hits");
    for (int count = 0; count < jsonArray.length(); count++) {
        JSONObject innerObject = jsonArray.getJSONObject(count);
        JSONObject recipe = innerObject.getJSONObject("recipe");
        FoodModel foodModel = new FoodModel();
        foodModel.setImage(recipe.getString("label"));
        foodModel.setLabel(recipe.getString("label"));
        foodModels.add(foodModel);
    }
    return foodModels;
}

FoodModel在这里

 public class FoodModel {

    private String label;
    private String image;

    public String getLabel() {
        return label;
    }

    public void setLabel(final String label) {
        this.label = label;
    }

    public String getImage() {
        return image;
    }

    public void setImage(final String image) {
        this.image = image;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    相关资源
    最近更新 更多