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

Android 解析 JSON 數據格式的兩種典型場景

編輯:關於 Android 程式設計

在與服務端交互時,JSON 是最常見的數據交換格式。就解析而言,可以把它分為兩類:一類是普通對象結構,另一類是帶數組的結構。下面分別說明。

一、普通形式

服務端返回的 JSON 如下:

{"userbean":{"Uid":"100196","Showname":"瘋狂的猴子","Avtar":null,"State":1}}

解析思路是:先判斷 HTTP 狀態碼,若為 200,則讀取響應流並構造 JSONObject,再逐個取出字段。

int res = 0;
res = httpClient.execute(httpPost).getStatusLine().getStatusCode();
if (res == 200) {
     HttpResponse httpResponse = httpClient.execute(httpPost);
     StringBuilder builder = new StringBuilder();
     BufferedReader bufferedReader2 = new BufferedReader(
         new InputStreamReader(httpResponse.getEntity().getContent()));
     for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine()) {
         builder.append(s);
     }
     JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("userbean");
     String Uid = jsonObject.getString("Uid");
     String Showname = jsonObject.getString("Showname");
     String Avtar = jsonObject.getString("Avtar");
     String State = jsonObject.getString("State");
}

二、帶數組形式

服務端返回的數據結構如下:

{"calendar":
    {"calendarlist":
            [
         {"calendar_id":"1705","title":"(親子)ddssd","category_name":"默認分類","showtime":"1288927800","endshowtime":"1288931400","allDay":false},
         {"calendar_id":"1706","title":"(旅行)","category_name":"默認分類","showtime":"1288933200","endshowtime":"1288936800","allDay":false}
            ]
    }
}

解析時,先取出 calendar 對象,再取出其中的 calendarlist 數組,然後遍歷數組,將每一項封裝成對象加入集合:

JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("calendar");
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
     CalendarInfo calendarInfo = new CalendarInfo();
     calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
     calendarInfo.setTitle(jsonObject2.getString("title"));
     calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
     calendarInfo.setShowtime(jsonObject2.getString("showtime"));
     calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
     calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
     calendarInfos.add(calendarInfo);
}

小結

總的來說,普通形式只需使用 JSONObject 逐層取值;而帶數組的形式則需要借助 JSONArray,將數據遍歷後轉換為 List 集合,方便後續使用。

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