Android json数据解析详解及实例代码
Android json数据解析详解
移动开发经常要与服务器数据交互,也常使用json数据格式,那就说说Android json解析。
1.最简单json格式解析如下:
//解析json
ry {
JSONTokener jsonParser = new JSONTokener(strResult);
JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
String strsportsTitle = jsonObj.getString("sportsTitle");
int nid= jsonObj.getInt("id");
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
字符串strResult就是需要解析json数据了。用过json数据格式都知道,json数据格式是一个键对应一个值。你可以先打印出原始数据strResult,就知道jsonObj.getString("sportsTitle");这双引号里面键是什么。
2.数组形式json数据解析如下:
try {
JSONArray jsonArray = new JSONArray(strResult);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.optJSONObject(i);
id[i] = jsonObj.getInt("id");
time[i] = jsonObj.getString("time");
users[i] = jsonObj.getString("users");
roomTitle[i] = jsonObj.getString("roomTitle");
}
} catch (JSONException e) {
System.out.println("Jsons parse error !");
e.printStackTrace();
}
3.json里面嵌套json数据解析如下:
try {
JSONArray jsonArray = new JSONArray(strResult);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.optJSONObject(i);
String strachievement = jsonObj.getString("achievement");
String strmember = jsonObj.getString("member");
try {
JSONTokener jsonParser1 = new JSONTokener(
achievement);
JSONObject jsonObj1 = (JSONObject) jsonParser1
.nextValue();
nametype[i] = jsonObj1.getString("name");
type[i] = jsonObj1.getString("type");
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
}
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
嵌套json数据,其实都是一样的。多解析一次而已。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
赞 (0)
