今天按照书上试了试json的解析
这里使用了两种方法来对json数据进行解析
1.利用JSONObject来解析 2.利用谷歌的开源库GSON来进行解析
一、利用JSONObject来进行解析
在服务器下建立json文件get_data.json如下:
{ "employees": [ { "firstName":"Bill" , "lastName":"Gates" }, { "firstName":"George" , "lastName":"Bush" }, { "firstName":"Thomas" , "lastName":"Carter" } ], "result":[ {"id":"5","version":"5.5","name":"Angry Birds"}, {"id":"6","version":"7.0","name":"Clash of Clans"}, {"id":"7","version":"3.5","name":"Hey Day"} ] } 然后再项目中建立代码:主要代码如下: ..................................
private void sendRequestWithHttpClient() {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://10.0.2.2/get_data.json");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
parseJSONWithJSONObject(response);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void parseJSONWithJSONObject(String response) {
// TODO Auto-generated method stub
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray resultArray = jsonObject.getJSONArray("result");
JSONObject subObject = resultArray.getJSONObject(0);
String id = subObject.getString("id");
String name = subObject.getString("name");
String version = subObject.getString("version");
Log.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}).start();
}
结果:
二、使用GSON来解析json
建立json文件get_data2.json
如下:
[{"id":"5","version":"5.5","name":"Angry Birds"},
{"id":"6","version":"7.0","name":"Clash of Clans"},
{"id":"7","version":"3.5","name":"Hey Day"}]
更改主要文件为:
private void parseJSONWidthGSON(String response) {
// TODO Auto-generated method stub
Gson gson =new Gson();
List<App> appList = gson.fromJson(response,new TypeToken<List<App>>(){}.getType());
for (App app : appList) {
Log.d("MainActivity","id is "+app.getId());
Log.d("MainActivity","id is "+app.getName());
Log.d("MainActivity","id is "+app.getVersion());
}
}
结果:
。。。。。。。