今天按照書上試了試json的解析json
這裏使用了兩種方法來對json數據進行解析服務器
1.利用JSONObject來解析 2.利用谷歌的開源庫GSON來進行解析app
1、利用JSONObject來進行解析ide
在服務器下創建json文件get_data.json以下:spa
{ "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() {blog
// TODO Auto-generated method stubutf-8
new Thread(new Runnable() {get
@Overrideit
public void run() {io
// 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();
}
結果:
2、使用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());
}
}
結果:
。。。。。。。