Package com. Practice. JSON;
Import org. JSON. jsonarray;
Import org. JSON. jsonexception;
Import org. JSON. jsonobject;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. util. log;
Public class jsondemo extends activity {
/*
* JSON parsing example. Str stores the JSON code, and the parsed data is output in logcat.
*/
String tag = "JSON message ";
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Detectjson ();
}
Private void detectjson (){
String STR = "{" +
"\" Date \ ": \" 2011-06-06 \ "," +
// Like is jsonobject
"\" Like \ ": {" +
"\" Name \ ": \" Garnett \ "," +
"\" Height \ ": \" 11cm \ "," +
"\" Age \ ": 35" +
"}," +
// Likelist is a jsonobject
"\" Likelist \ ":" +
"{\" List \ ":" +
"[" +
// Jsonobject
"{" +
"\" Name \ ": \" Rose \ "," +
"\" Height \ ": \" 190cm \ "," +
"\" Age \ ": 23" +
"}," +
// Jsonobject
"{" +
"\" Name \ ": \" Kobe \ "," +
"\" Height \ ": \" 198cm \ "," +
"\" Age \ ": 33" +
"}" +
"]" +
"}" +
"}";
Try {
Jsonobject datajson = new jsonobject (STR );
Log. D (TAG, datajson. getstring ("date "));
Jsonobject nbajson = datajson. getjsonobject ("like ");
Log. D (TAG, nbajson. getstring ("name "));
Log. D (TAG, nbajson. getstring ("height "));
Log. D (TAG, nbajson. Get ("Age"). tostring ());
Jsonobject listjson = datajson. getjsonobject ("likelist ");
Jsonarray arrayjson = listjson. getjsonarray ("list ");
For (INT I = 0; I <arrayjson. Length (); I ++ ){
Jsonobject tempjson = arrayjson. optjsonobject (I );
Log. D (TAG, tempjson. getstring ("name "));
Log. D (TAG, tempjson. getstring ("height "));
Log. D (TAG, tempjson. getstring ("Age"). tostring ());
}
} Catch (jsonexception e ){
System. Out. println ("something wrong ...");
E. printstacktrace ();
}
}
}
Note: braces {} indicate jsonobject
Brackets [] indicate jsonarray
Reference: http://www.oschina.net/code/snippet_176897_7317