The examples in this article describe how Android programmatically parses JSON-formatted data. Share to everyone for your reference, specific as follows:
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 {/* Parse JSON example, STR saves JSON code, parsed data in logcat output */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\ ": \" 2.11cm\ "," + "\" age\ ":" + "}," +//likelist is a jsonobject " \ "Likelist\": "+" {\ "list\": "+" ["+//Here is also jsonobject" {"+" \ "name\": \ "rose\", "+" \ "height\ ": \" 190cm\ "," + "\" age\ ": 23" + "}," +//Here is also jsonobject "{" + "\" name\ ":" Kobe Bryant \ "" + "\" Heigh
T\ ": \" 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 ());
The catch (Jsonexception e) {System.out.println ("something wrong ...");
E.printstacktrace (); }
}
}
I hope this article will help you with your Android programming.