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

Android 客戶端取得並解析伺服器 JSON 資料的實作

編輯:關於 Android 程式設計

在 Android 應用程式中,常需要從伺服器取得 JSON 資料,再將內容呈現在畫面上。整個流程通常包含三個步驟:先透過網路連線取得資料,接著解析 JSON 字串,最後將結果綁定到 TextView、ListView 或其他元件。

從伺服器取得 JSON 資料

使用 HttpURLConnection

HttpURLConnection 是 Android 中常見的網路連線方式。可先建立 URL 物件,開啟連線後讀取輸入串流,再將位元組資料轉成字串。

URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
while ((len = inStream.read(data)) != -1) {
    outStream.write(data, 0, len);
}
inStream.close();
return new String(outStream.toByteArray());

使用 HttpClient

若需要送出 POST 參數,也可使用 HttpClient。建立 HttpPost 後,可加入 NameValuePair 參數,再執行請求並取得回應內容。

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResp = httpClient.execute(httpPost);
if (httpResp.getStatusLine().getStatusCode() == 200) {
    result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
}

解析 JSON 資料

伺服器回傳的 JSON 若是陣列結構,通常會以方括號開頭。解析時可先建立 JSONArray,再取出其中的 JSONObject,最後透過 getString 或 getInt 取得欄位。

JSONArray jsonArray = new JSONArray(jsonStr);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String logo = jsonObject.getString("logo");
String logoLunbo = jsonObject.getString("logoLunbo");
String biaoTi = jsonObject.getString("biaoTi");

若資料筆數較多,可依序走訪 JSONArray,將每一筆資料放入 List 或 ArrayList,方便後續交給 ListView 或 GridView 顯示。

將資料呈現在畫面上

若只是單純文字,可直接將解析後的字串設定給 TextView。若使用 ListView,則需要建立 Adapter,將資料集合與版面配置中的元件互相對應。常見做法是自訂 BaseAdapter,在 getView 中判斷元件類型,再設定文字或圖片。

載入網路圖片

JSON 中的圖片欄位通常只是 URL 字串,若要顯示圖片,需再透過網路下載並解碼成 Bitmap。可將此流程封裝成工具類別,方便多處重複使用。

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
    InputStream inStream = conn.getInputStream();
    bitmap = BitmapFactory.decodeStream(inStream);
}

執行緒與使用者體驗

網路請求與圖片下載可能耗費時間,不應直接放在主執行緒中執行,否則可能造成畫面卡頓或 ANR。實務上會建立子執行緒處理下載與解析,完成後再透過 Handler 將結果送回主執行緒更新 UI。

權限提醒

若應用程式需要連線網路,記得在 AndroidManifest.xml 中宣告 INTERNET 權限。缺少此權限時,即使程式碼正確,也可能無法實際連線伺服器。

整體而言,取得 JSON 的關鍵在於穩定連線、正確解析與即時更新畫面。將網路請求、資料解析與 UI 更新分離,不僅能提升可讀性,也方便後續維護與擴充。

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