關於JSON的解析,下面先貼一段代碼:
private void parseJSONinfodata(String infodata) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(infodata);
} catch (JSONException e) {
}
if (jsonArray == null) return;
length = jsonArray.length();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
} catch (JSONException e) {
}
if (jsonObject == null) continue;
String begintime = "", endtime = "", user = "";
try {
begintime = jsonObject.getString("begintime");
} catch (JSONException e) {
}
try {
endtime = jsonObject.getString("endtime");
} catch (JSONException e) {
}
try {
user = jsonObject.getString("user");
} catch (JSONException e) {
}
BeginTime[i] = begintime;
EndTime[i] = endtime;
User[i] = user;
Log.d(TAG, "begintime is " + begintime);
Log.d(TAG, "endtime is " + endtime);
Log.d(TAG, "user is " + user);
}
}
首先將String類型的數據轉化爲JSONArray,然後以此從JSONArray中讀取JSONObject,之後從JSONObject中讀取相應的數據。
下面要注意幾點,將String轉化爲JSONArray時,從JSONArray中讀取JSONObject時,從JSONObject中get數據時,要進行JSONExecption的判斷。
還可以使用Google的開源庫GSON,這可以大量的簡化代碼。