Today we will introduce json data parsing. We use JSONObject and JSONArray in Android to parse json data. For more information, see android Developers.
String strJson = "{" students ": [{" name ":" Jack "," age ": 12 },{" name ":" Vista "," age ": 23 },{ "name": "Kaka", "age": 22 },{ "name": "Hony", "age": 31}]} ";
Try {
JSONObject jo = new JSONObject (strJson );
JSONArray jsonArray = (JSONArray) jo. get ("students ");
For (int I = 0; I <jsonArray. length (); ++ I ){
JSONObject o = (JSONObject) jsonArray. get (I );
System. out. println ("name:" + o. getString ("name") + "," + "age :"
+ O. getInt ("age "));
}
} Catch (JSONException e ){
E. printStackTrace ();
}
2. Use JsonReader in gson to parse json data
Try {
String string = "{" class ": 1," students ": [{" name ":" jack "," age ": 21 },{" name ": "kaka", "age": 21 },{ "name": "lucy", "age": 21}]} ";
StringReader sr = new StringReader (string );
JsonReader jr = new JsonReader (sr );
Jr. beginObject ();
If (jr. nextName (). contains ("class ")){
System. out. println ("class:" + jr. nextString ());
If (jr. nextName (). equals ("students ")){
Jr. beginArray ();
While (jr. hasNext ()){
Jr. beginObject ();
If (jr. nextName (). equals ("name "))
System. out. print ("name:" + jr. nextString ());
If (jr. nextName (). equals ("age ")){
System. out. println (", age:" + jr. nextInt ());
}
Jr. endObject ();
}
Jr. endArray ();
}
}
Jr. endObject ();
} Catch (FileNotFoundException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Json parser library gson: http://code.google.com/p/google-gson/