如何从JSON(LastFM API)中提取图像的URL

时间:2017-05-31 16:57:12

标签: java android json

我是JSON使用的初学者。

所以我尝试从JSON回复中提取图像的URL。

这是允许我获取数组的代码:

            // Instantiate the RequestQueue.
            RequestQueue queue = Volley.newRequestQueue(getActivity());
            //String url ="http://www.google.com";
            String url = "http://ws.audioscrobbler.com/2.0/?method=album.search&album="+albumName+"&api_key=c51f8eb36bad&format=json";


            // Request a string response from the provided URL.
            StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the first 500 characters of the response string.
                            //mTextView.setText("Response is: "+ response.substring(0,500));
                            Log.i("RESPONSE","Response is: "+ response);

                            JSONObject jsono = new JSONObject();
                            try {
                                jsono = new JSONObject(response);
                                //String url = jsono.getString("results");


                                //Log.i("RESPONSE",url);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.d ("RESPONSE",e.getMessage());
                            }
                            JSONArray jsonArray = new JSONArray();
                            try {
                                jsonArray = jsono.getJSONObject("results").getJSONObject("albummatches").getJSONArray("album");
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.d ("RESPONSE",e.getMessage());
                            }
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject object = new JSONObject();
                                try {
                                    object = jsonArray.getJSONObject(i);
                                    Log.i("RESPONSE",object.getString("image"));

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

                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("RESPONSE","That didn't work!");
                }
            });
            queue.add(stringRequest);

以下是JSON答案中此部分的结构:

    {

    "album": [
        {
            "name": "DD Y Ponle Play",
            "artist": "Jumbo",
            "id": "2528039",
            "url": "http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play",
            "image": [
                {
                    "#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
                    "size": "small"
                },
                {
                    "#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
                    "size": "medium"
                },
                {
                    "#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
                    "size": "large"
                },
                {
                    "#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
                    "size": "extralarge"
                }
            ]
        }
    ]
}

如何获取给定尺寸的图像的网址?

非常感谢你的建议。

5 个答案:

答案 0 :(得分:1)

您可以使用谷歌GSON。将其作为依赖项导入

首先创建一个专辑类。

public class Albums {

private List<Album> album;

public List<Album> getAlbum() {
    return album;
}

public class Album{
    private String name;
    private String artist;
    private String id;
    private String url;

    public String getName() {
        return name;
    }

    public String getArtist() {
        return artist;
    }

    public String getId() {
        return id;
    }

    public String getUrl() {
        return url;
    }

    public List<Image> getImage() {
        return image;
    }

    public class Image {
        @SerializedName("#text")
        private String text;
        private String size;

        public String getText() {
            return text;
        }

        public String getSize() {
            return size;
        }
    }

    private List<Image> image;
}

}

现在,在您获得上述JSON对象的代码中,请尝试以下代码

Gson gson = new Gson();

// Im assuming "response" as the above JSON object
Albums albums = gson.fromJson(response.optString("album"),Albums.class);

这会将您的json映射到java对象。(注意:您可以根据需要从POJO中删除不需要的对象)

您可以使用getter函数

获取图像

答案 1 :(得分:0)

正如Raghunandan所提到的,当你需要提取JSONArray时,你正在提取一个JSONObject,然后从那个数组中提取一个JSONObject。

尝试使用GSON之类的库来简化此任务,或者参考这个小型JSON库I wrote

答案 2 :(得分:0)

解析JSON数组实际上非常简单:

JSONArray jsonarray = new JSONArray("album");
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    String url = jsonobject.getString("url");
}

希望它有所帮助!!!

答案 3 :(得分:0)

JSON只不过是键值表示。抓住它并不难。你的代码应该是这样的,

更新:这只会打印包含size = medium

的网址
    String response = "{\"album\":[{\"name\":\"DD Y Ponle Play\",\"artist\":\"Jumbo\",\"id\":\"2528039\",\"url\":\"http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play\",\"image\":[{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"small\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"medium\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"large\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"extralarge\"}]}]}";

    JSONObject myObject = new JSONObject(response);
    JSONArray myArray = myObject.getJSONArray( "album" );

    for(int i=0; i<myArray.length(); i++)
    {
        JSONObject myIterator = myArray.getJSONObject( i );
        JSONArray arrayOne = myIterator.getJSONArray( "image" );

        for(int j=0; j<arrayOne.length(); j++)
        {
            JSONObject myInnerIterator = arrayOne.getJSONObject( j );               
            if(myInnerIterator.has( "size" ))//check if 'size' key is present
                if(myInnerIterator.getString( "size" ).equalsIgnoreCase( "medium" ))
                    System.out.println( myInnerIterator.getString( "#text" ) );
        }
    }

答案 4 :(得分:0)

找到图像的网址&#34; medium&#34;我确实喜欢这个:

                            ArrayList<String> listUrl = new ArrayList<String>();
                            for(int i=0; i<jsonArray.length(); i++)
                            {
                                JSONObject myIterator = null;
                                try {
                                    myIterator = jsonArray.getJSONObject( i );
                                    JSONArray arrayOne = myIterator.getJSONArray( "image" );

                                    for(int j=0; j<arrayOne.length(); j++)
                                    {
                                        JSONObject myInnerIterator = arrayOne.getJSONObject( j );
                                        String s = myInnerIterator.getString( "size" )+myInnerIterator.getString("#text");
                                        if (s.contains("medium") && s.contains("https")){
                                            listUrl.add (s.replace("medium",""));
                                            Log.i("RESPONSE",s.replace("medium",""));
                                        }

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

我认为必须有更好的......但是它可以做到这一点!