Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖文混排 JSON 解析實戰:金山詞霸每日一句 API 完整拆解

編輯:關於 Android 程式設計

很多學習 Android 的朋友在入門階段都會遇到同一道坎:拿到一個網路介面,卻不知道怎麼把返回的 JSON 字串變成畫面上的一張圖、一行字。本文以金山詞霸「每日一句」開放介面為例,完整走一遍從請求資料、解析欄位到異步載入圖片的流程,適合當作圖文混排的第一個練習專案。

一、先看清楚資料長什麼樣

介面位址為 https://open.iciba.com/dsapi/,以 GET 方式請求即可,回傳的是一段 JSON 物件:

{
  sid: 737,
  tts: https://news.iciba.com/admin/tts/2013-12-11.mp3,
  content: I don't want us to be together because we have to,
           I want us to be together because we want to.,
  note: 我不希望我們因為「不得不」而在一起,我希望我們是因為想在一起而在一起。,
  translation: 詞霸小編的投稿說明與電影出處介紹……,
  picture: https://cdn.iciba.com/news/word/2013-12-11.jpg,
  picture2: https://cdn.iciba.com/news/word/big_2013-12-11b.jpg,
  caption: 詞霸每日一句,
  dateline: 2013-12-11,
  s_pv: 8693,
  sp_pv: 2090,
  tags: [{ id: 9, name: 愛情 }, { id: 14, name: 電影經典 }],
  fenxiang_img: https://cdn.iciba.com/web/news/longweibo/imag/2013-12-11.jpg
}

二、欄位意義對照表

解析之前先把每個 key 的用途弄清楚,後面上程式才不會亂:

  • sid:每日一句的唯一 ID。
  • tts:朗讀用的 mp3 音檔位址,可以搭配 MediaPlayer 發音。
  • content:英文原文。
  • note:中文翻譯。
  • translation:詞霸小編的補充說明。
  • picture:配圖位址(一般尺寸)。
  • picture2:配圖位址(大尺寸),適合詳情頁。
  • caption:標題文字。
  • dateline:對應日期。
  • s_pv / sp_pv:瀏覽數與語音評測瀏覽數。
  • tags:分類標籤陣列,每筆含 id 與 name。
  • fenxiang_img:分享用的合成圖。

三、最終呈現效果

畫面上方是配圖,下方依序是英文原文、中文翻譯、日期與小編按語,就是一個典型的圖文卡片。

四、用 AsyncTask 異步行網路請求

Android 3.0 之後主執行緒不能做網路 I/O,否則直接拋 NetworkOnMainThreadException。最直覺的做法是繼承 AsyncTask,把請求與解析都放到 doInBackground() 裡:

class Load extends AsyncTask<String, String, String> {
    private final String url = "https://open.iciba.com/dsapi/";
    private ProgressDialog pdlg;
    private String jsonstr = "";
    private JSONObject json = null;
    private String engstr, chistr, imagurl, timestr, fromstr;

    @Override
    protected String doInBackground(String... params) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httppost);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();

            jsonstr = sb.toString();
            json = new JSONObject(jsonstr);

            engstr   = json.getString("content");
            chistr   = json.getString("note");
            imagurl  = json.getString("picture");
            timestr  = json.getString("dateline");
            fromstr  = json.getString("translation");

            // tags 是陣列,必須另外取出來遍歷
            JSONArray array = json.getJSONArray("tags");
            for (int i = 0; i < array.length(); i++) {
                JSONObject tag = array.getJSONObject(i);
                Log.d("tag", tag.getInt("id") + " / " + tag.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonstr;
    }

    @Override
    protected void onPostExecute(String result) {
        if (pdlg != null) pdlg.dismiss();
        // 在這裡把 engstr、chistr、imagurl 綁回畫面元件
        super.onPostExecute(result);
    }
}

幾個實務上要注意的點:字串拼接要用 StringBuilder 而不是 +=;讀完資料務必關掉串流;解析放在背景執行緒、更新 UI 放在 onPostExecute(),這是 AsyncTask 的鐵則。

五、圖片不能同步載入:自己寫一個 ImageLoader

網路圖片如果直接在 doInBackground() 或主執行緒下載,會讓整個列表卡死,而且每次都重新抓圖會讓流量與記憶體雙雙爆掉。實務上的標準做法是「記憶體快取 + 檔案快取 + 執行緒池」三層結構。

下面這個 ImageLoader 就是這個思路的最小可用版本:

public class ImageLoader {
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private final Map<ImageView, String> imageViews =
            Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    public ImageLoader(Context context) {
        fileCache = new FileCache(context);
        executorService = Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.drug_trans;

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        } else {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id); // 先放佔位圖
        }
    }

    private void queuePhoto(String url, ImageView imageView) {
        PhotoToLoad p = new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);
        Bitmap b = decodeFile(f);          // 先找 SD 卡快取
        if (b != null) return b;
        try {                               // 快取沒有才走網路
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            return decodeFile(f);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 先量尺寸、再降采样,避免大圖直接造成 OOM
    private Bitmap decodeFile(File f) {
        try {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private class PhotoToLoad {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i) { url = u; imageView = i; }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad p) { this.photoToLoad = p; }

        @Override
        public void run() {
            if (imageViewReused(photoToLoad)) return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad)) return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            Activity a = (Activity) photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }

        boolean imageViewReused(PhotoToLoad p) {
            String tag = imageViews.get(p.imageView);
            return tag == null || !tag.equals(p.url);
        }
    }

    class BitmapDisplayer implements Runnable {
        Bitmap bmp;
        PhotoToLoad p;
        BitmapDisplayer(Bitmap b, PhotoToLoad p) { this.bmp = b; this.p = p; }
        public void run() {
            if (!imageViewReused(p) && bmp != null) p.imageView.setImageBitmap(bmp);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}

這裡有兩個關鍵細節值得多說兩句。第一是 WeakHashMap 搭配 imageViews 標記,用來解決 ListView 回收造成的「圖片錯位」問題——當 ImageView 被回收去綁定另一筆資料時,原本的執行緒回來就應該放棄設定圖片。第二是 inSampleSize 降採樣,與其把一張上千像素的原圖塞進記憶體,不如先量邊長再等比縮小,這一步往往是列表順不順滑的分水嶺。

六、小結

整個流程拆開來其實只有四件事:發請求、解析 JSON、異步載圖、綁定 UI。難點不在語法,而在「哪一段該放在哪個執行緒」以及「快取怎麼設計」。把這兩個觀念吃透,之後換成任何一個圖文介面都能快速上手。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved