样例JSON格式
[
{"id":"5", "version":"1", "name":"Clash of Clans"},
{"id":"6", "version":"2", "name":"Boom Beach"},
{"id":"5", "version":"1", "name":"Okey Google"}
]
1.使用JsonObject解析
还是以上文xml解析的activity为基础,将parseXml
方法替换成parseJsonWithJSONObject
方法
private void parseJsonWithJSONObject(String responseString) {
try {
JSONArray array = new JSONArray(responseString);
for (int i = 0; i < array.length(); i++) {
JSONObject jObject = array.getJSONObject(i);
String id = jObject.getString("id");
String name = jObject.getString("name");
String version = jObject.getString("version");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
2.使用Gson解析
Gson是谷歌提供的用于解析Json数据的开源库,可以以十分简单的方式来解析Json数据
基本用法
Gson gson = new Gson(); //create a new Gson object;
AppBean apps = gson.fromJson(responseString, AppBean.class); //parse an Json Object
List<AppBean> appList = gson.fromJson(responseString
, new TypeToken<List<AppBean>>(){}.getType()); //parse an Json array
Sample Code
private void parseJsonWithGson(String responseString) {
Gson gson = new Gson();
//parse an Json array
List<AppBean> appList = gson.fromJson(responseString, new TypeToken<List<AppBean>>(){}.getType());
for(AppBean app : appList) {
//do whatever you want with data
Log.i("lyh", app.toString());
}
}
网友评论