关于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,这可以大量的简化代码。