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

Android 解析 JSON 資料的實作與範例說明

編輯:關於 Android 程式設計

JSON 是一種輕量級的資料格式,資料體積小、便於傳輸、易於解析,是行動應用與伺服器溝通時的熱門選擇。本文示範如何在 Android 中發送 HTTP 請求取得 JSON,並逐層解析其中的物件與陣列。

步驟一:建立 JSON 工具類

先封裝一個 JsonUtil 工具類,負責發送請求並把回應字串轉為 JSONObject:

public class JsonUtil {
    private static final String TAG = "JSONUTIL";
    public static JSONObject getJSON(String url) throws Exception {
        return new JSONObject(getRequest(url));
    }
    protected static String getRequest(String url) {
        return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
    }
    protected static String getRequest(String url, DefaultHttpClient client) {
        String result = null;
        int statusCode = 0;
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = client.execute(httpGet);
            statusCode = httpResponse.getStatusLine().getStatusCode(); // 200 表示請求成功
            result = parseInputStream(httpResponse.getEntity());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpGet.abort();
        }
        return result;
    }
    private static String parseInputStream(HttpEntity entity) {
        StringBuilder sb = null;
        try {
            sb = new StringBuilder("");
            InputStream inputStream = entity.getContent();
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) > -1) {
                sb.append(new String(buffer, 0, length));
            }
            return sb.toString();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}

步驟二:取得並解析資料

解析時,透過 getJSONArray 取得陣列、getString 與 getInt 取得各欄位值:

/* https://10.0.2.2:8080/index.jsp
 * { students:[{name:'Livingstone',age:25},{name:'LS',age:26}], class:'09GIS' }
 */
private void Livingstone() {
    try {
        String URL = "https://10.0.2.2:8080/index.jsp";
        JSONObject jObj = JsonUtil.getJSON(URL);        // 取得整個 JSON 物件
        JSONArray jArr = jObj.getJSONArray("students"); // 取得學生陣列
        String classname = jObj.getString("class");     // 取得班級
        JSONObject j1 = jArr.getJSONObject(0);          // 取得第一個學生物件
        String studentInfo = jArr.length() + "個學生" + j1.getString("name") + j1.getInt("age");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

兩個重要的實務提醒

首先,關於模擬器訪問本機網站:不能用 localhost:8080 或 127.0.0.1:8080,因為模擬器會把 localhost 指向自身。此時應使用專用的主機名 10.0.2.2,它才是模擬器設定用來訪問宿主電腦的位址。

其次,關於線程:網路請求屬於耗時操作,必須封裝到一個新線程中執行,絕不能放在主線程,否則會導致界面卡頓甚至引發錯誤。

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