我无法找到这个问题的详细答案,或者至少没有找到我能理解的答案.
我正在尝试设置Volley来从iTunes中下载JSON对象.然后我想解析对象,以获取他们的图像URL.
例如,这是iTunes JSON对象URL
String url = "https://itunes.apple.com/search?term=michael+jackson";
String url = "https://itunes.apple.com/search?term=michael+jackson"; JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.GET,url,null,new Downloader.Response.Listener // Cannot resolve symbol Listener <JSONObject>() { @Override public void onResponse(JSONObject response) { // the response is already constructed as a JSONObject! try { response = response.getJSONObject("args"); String site = response.getString("site"),network = response.getString("network"); System.out.println("Site: "+site+"\nNetwork: "+network); } catch (JSONException e) { e.printStackTrace(); } } },new Downloader.Response.ErrorListener // Cannot resolve symbol ErrorListener () { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); Volley.newRequestQueue(this).add(jsonRequest);
最后一句话是
Volley.newRequestQueue(this).add(jsonRequest);
据推测,我现在有JSON对象?但是我如何访问和解析它?
解决方法
使用您的Url,您可以使用以下示例代码:
RequestQueue requestQueue = Volley.newRequestQueue(this); String url = "https://itunes.apple.com/search?term=michael+jackson"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (response != null) { int resultCount = response.optInt("resultCount"); if (resultCount > 0) { Gson gson = new Gson(); JSONArray jsonArray = response.optJSONArray("results"); if (jsonArray != null) { SongInfo[] songs = gson.fromJson(jsonArray.toString(),SongInfo[].class); if (songs != null && songs.length > 0) { for (SongInfo song : songs) { Log.i("LOG",song.trackViewUrl); } } } } } } },new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("LOG",error.toString()); } }); requestQueue.add(jsonObjectRequest);
SongInfo类:
public class SongInfo { public String wrapperType; public String kind; public Integer artistId; public Integer collectionId; public Integer trackId; public String artistName; public String collectionName; public String trackName; public String collectionCensoredName; public String trackCensoredName; public String artistViewUrl; public String collectionViewUrl; public String trackViewUrl; public String previewUrl; public String artworkUrl30; public String artworkUrl60; public String artworkUrl100; public Float collectionPrice; public Float trackPrice; public String releaseDate; public String collectionExplicitness; public String trackExplicitness; public Integer discCount; public Integer discNumber; public Integer trackCount; public Integer trackNumber; public Integer trackTimeMillis; public String country; public String currency; public String primaryGenreName; public String radioStationUrl; public Boolean isStreamable; }
在build.gradle文件中:
compile 'com.mcxiaoke.volley:library:1.0.19' compile 'com.google.code.gson:gson:2.5'
希望这可以帮助!