首页 > 解决方案 > 如何使用 volley 在 android studio 中获取 Json 数组数据?

问题描述

我有一个 JSON 编码数组,如下所示:-

{
"imager": [{
    "title": "Guru",
    "images": ["images\/6.png", "images\/androidIntro.png", "images\/barretr_Earth.png"]
}]

}

我的问题是我想一张一张地从图像数组中获取所有图像,以便我可以在 imageview 上显示图像。我的主要目标是只显示一次标题并显示与标题相关的所有图像,我已经在整个互联网和堆栈流中进行了搜索,但我无法找到正确的答案有人可以帮我解决这个问题吗?我正在使用 Volley Libabry 这是我的代码:-

  url = "myurl";

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {


                JSONArray jsonArray = response.getJSONArray("imager");

                for (int i=0; i<jsonArray.length(); i++)
                {
                    JSONObject object = jsonArray.getJSONObject(i);
                    String title = object.getString("title");
                    String images = object.getString("images");

                   // what to do here now?? help me?
                }

如果我设置

textview.setText(images);
output will be like this:-
["images\/6.png","images\/androidIntro.png","images\/barretr_Earth.png"]

但我只想要图像/6.png 图像/androidIntro.png 图像/battetr_Earth.png

这样我就可以在 imageview 中显示这些所有图像。

标签: androidarraysjsonsorting

解决方案


您必须将"images"标签作为数组处理。

代替

String images = object.getString("images");

利用

JsonArray images = object.getJSONArray("images");
for (int j=0; j<images.length(); j++) {
    String image = images.getString(j)
    // image will be 
    // j = 0 -> "images\/6.png"
    // j = 1 -> "images\/androidIntro.png"
    // j = 2 -> "images\/barretr_Earth.png"
}

推荐阅读