Today, I tried to test the JSON with the book.
Two methods are used to parse the JSON data.
1. Use Jsonobject to parse 2. Use Google's Open Source Library Gson to parse
First, the use of Jsonobject to analyze
Create a JSON file under the server Get_data.json as follows:
{"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 "}]}
Then build the code in the project:
The main code is as follows:
..................................
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 () = = () {
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 ();
}
Results:
Second, using Gson to parse JSON
Create a JSON file Get_data2.json
As follows:
[{"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"}]
Change the primary file to:
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 ());
}
}
Results:
。。。。。。。
JSON parsing in Android