Android的循环通过JSON下载图像
问题描述:
我使用包含图像的URL文件名以下JSON字符串:Android的循环通过JSON下载图像
{
"images": [
{
"image_url": "https:\/\/placeimg.com\/150\/50\/nature",
"image_filename": "placeimg_150_50_nature.jpg"
},
{
"image_url": "https:\/\/placeimg.com\/150\/50\/nature",
"image_filename": "placeimg_150_50_nature.jpg"
}
]
}
我也是用这个功能来下载该作品完美的图片到我的SD卡:
public void downloadFile(String uRl, String fileName) {
File file = new File(getAppRootDir()
+ "/images", fileName);
File direct = new File(getAppRootDir()
+ "/images");
if (!direct.exists()) {
direct.mkdirs();
}
if (!file.exists()) {
DownloadManager mgr = (DownloadManager) MainActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir(getAppRootDir() + "/images", fileName);
mgr.enqueue(request);
}
}
我该如何循环浏览JSON以获取每个条目的image_url和image_filename?
答
回应是JSONObject
其中内容JSONArray
与JSONObject's.final JSONObject
的密钥images
内容两个键。
获取image_url
和image_filename
键值:
JSONObject jsonObject=new JSONObject(<response_string>);
// get images JSONArray from jsonObject
JSONArray jsonArrImages=jsonObject.getJSONArray("images");
for(int index=0;index<jsonArrImages.length(); index++) {
JSONObject jsonObjectInner=jsonArrImages.getJSONObject(index);
String img_url=jsonObjectInner.optString("image_url")+"/"
+jsonObjectInner.optString("image_filename");
// download image from url
downloadFile(img_url,jsonObjectInner.optString("image_filename"));
}
+1
这工作得很好!我不得不围绕它尝试/捕获,但它的工作完美无瑕。 –
哪些问题,你得到? –
只需查看GSON库。为您处理解析。 –