2015-11-04 107 views
-1

我使用包含圖像的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?

+0

哪些問題,你得到? –

+0

只需查看GSON庫。爲您處理解析。 –

回答

1

迴應是JSONObject其中內容JSONArray與JSONObject's.final JSONObject的密鑰images內容兩個鍵。

獲取image_urlimage_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

這工作得很好!我不得不圍繞它嘗試/捕獲,但它的工作完美無瑕。 –