JSON has two representations of structures, objects, and arrays.
The object structure starts with "{" Curly braces and ends with "}" curly braces. The middle section consists of 0 or more "key (key)" pairs consisting of "," separated by "/value", the keywords and values separated by ":", and the grammatical structure such as code.
Where the keyword is a string, and the value can be a string, a value, a true,false,null, an object, or an array
The array structure ends with "[" Start, "]". The middle consists of 0 or more lists of values separated by ",", grammatical structures such as code.
Case *******************************************
The Bean class is posted here first
Result
Package Com.lw.bean;import Java.util.arraylist;import Java.util.list;public class Result {//result value, if the 2 description returns the correct private int Result;private list<person> persondata = new arraylist<person> ();p ublic int GetResult () {return result ;} public void Setresult (int result) {This.result = result;} Public list<person> Getpersondata () {return persondata;} public void Setpersondata (list<person> persondata) {this.persondata = Persondata;}}
Person
Package Com.lw.bean;import Java.util.list;public class Person {private string url;private string name;private int Age;pri Vate list<schoolinfo> schoolinfo;public list<schoolinfo> getschoolinfo () {return SchoolInfo;} public void Setschoolinfo (list<schoolinfo> schoolinfo) {this.schoolinfo = Schoolinfo;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String GetUrl () {return URL;} public void SetUrl (String url) {this.url = URL;}}
Schoolinfo
Package Com.lw.bean;public class Schoolinfo {private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;}}
Next, paste the layout file of the main interface layout and each item in the ListView
Json.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent " android:o rientation= "vertical" > <listview android:id= "@+id/listview" android:layout_width= "Fill_ Parent " android:layout_height=" Fill_parent "/></linearlayout>
Item.xml
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_height = "Match_parent" android:orientation= "vertical" > <imageview android:id= "@+id/imageview" Android: Layout_width= "150DP" android:layout_height= "100DP" android:layout_alignparentleft= "true"/> <relati Velayout android:layout_width= "fill_parent" android:layout_height= "100DP" android:layout_torightof= "@ Id/imageview "android:padding=" 10DP "> <textview android:id=" @+id/name "Android: Layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "name"/> < ; TextView android:id= "@+id/age" android:layout_width= "Fill_parent" android:layout_height= " Wrap_content "Android: layout_below= "@id/name" android:text= "Age"/> <textview android:id= "@+id/school1" Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_below= "@id/age" android:text= "School1" android:textsize= "20DP"/> <textview androi D:id= "@+id/school2" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:layout_below= "@id/school1" android:text= "School2" android:textsize= "20DP"/> </r Elativelayout></relativelayout>
Then post the main activity.
Jsonactivyty
Package Com.lw.http01;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.widget.listview;public class Jsonactivyty extends Activity {private ListView listview;private Jsonadapter Jsonadapter;private Handler Handler = new Handler (), @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate);/** json layout file, there is only one ListView control */setcontentview (R.layout.json); listview = ( ListView) Findviewbyid (r.id.listview);/** * There was no data at first, and then from the server gets the new data and UI interface in the child thread * */jsonadapter = new Jsonadapter ( this);/** * Service level Http://192.168.79.101:8080/testAndroidServer/jsonServlet can get to JSON data * There is no service-side code posted here, it is enough to know the above word */new Jsonthread ("Http://192.168.79.101:8080/testAndroidServer/jsonServlet", this, ListView, Jsonadapter, handler). Start ();}}
The next step is to post it first
Jsonthread
Package Com.lw.http01;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Java.util.arraylist;import Java.util.List;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Android.content.Context;import Android.os.handler;import Android.widget.listview;import Android.widget.toast;import Com.lw.bean.Person;import Com.lw.bean.schoolinfo;public class Jsonthread extends Thread {/** * URL is server address * context is environment and requires toast hint * ListView is required Setada Pter Settings Adapter * Jsonadapter is required to set the data * handler is required to update UI */private String url;private Context context;private ListView Listv Iew;private jsonadapter jsonadapter;private Handler handler;public jsonthread (String URL, context context, ListView Listview,jsonadapter Jsonadapter, Handler Handler) {this.url = Url;this.context = Context;this.listview = ListView; This.jsonadapter = Jsonadapter;this.handler = handler;} @Overridepublic void Run () {try {//Create URL object, and set the corresponding parameterNumber of URLs httpurl = new URL (URL);//Open connection HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setreadtimeout Conn.setrequestmethod ("GET");//Read data from the server, need to read the stream BufferedReader reader = new BufferedReader ( New InputStreamReader (Conn.getinputstream ()));//After reading, it is stored in the StringBuffer container stringbuffer sb = new StringBuffer (); String str = ""; while ((str = reader.readline ()) = null) {//When Read is complete, add to Container sb.append (str);} The JSON string to be read to resolves to the Person object collection final list<person> Parsejson = Parsejson (sb.tostring ());// Handler update data in child threads Handler.post (new Runnable () {@Overridepublic void Run () {//Set data to Adapter view, Make it available to data jsonadapter.setdata (Parsejson);//Set Adapter Listview.setadapter (Jsonadapter);}});} catch (Exception e) {e.printstacktrace ();}} /*** * Parse the JSON string data returned by the service side, because the item in the adapter view is a person object, so returning the person collection is a native parsing of Android */private list<person> Parsejson (String JSON) {//json parsed, returns the collection object of person list<person> persons = new arraylist<person> (); try {/** * { "1": [{Person Object},{person object},{Person Object}]} * So the whole is a JSON object, not a JSON array * So create a Jsonobject object */jsonobject jsonobj = new Jsonobject (JSON);//Get the result value int result = Jsonobj.getint ("result");//If the 2 description returns the correct if (result = = 2) {//Gets the JSON array of person jsonarray persondata = Jsonobj.getjsonarray ("Persondata");/** * Loops parse each Person object */for (int i = 0; i < persondata.length (); i++) {//Create person object P Erson personobj = new Person (); list<schoolinfo> Scinfos = new arraylist<schoolinfo> ();//Gets the person object of each JSON type from the JSON object array jsonobject person = Persondata.getjsonobject (i);//sets the value of the person object of the JSON type for the person object Personobj.setname (person.getstring ("name")); Personobj.setage (Person.getint ("Age"));p Ersonobj.seturl (person.getstring ("url"));/** Get school information in a JSON-type person * /jsonarray SCS = Person.getjsonarray ("Schoolinfo"); for (int j = 0; J < Scs.length (); j + +) {Schoolinfo schoolobj = new S Choolinfo (); Jsonobject School = Scs.getjsonobject (j); Schoolobj.setname (school.getstring ("name")); Scinfos.add (schoolobj);} Personobj.setschoolinfo (Scinfos);p Ersons.add (personobj);}} else {toast.maketext (context, "error", 1);}} catch (Jsonexception e) {e.printstacktrace ();} return persons;}}
Next, the code for the adapter is posted
Jsonadapter
Package Com.lw.http01;import Java.util.list;import Android.content.context;import android.os.handler;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;import Com.lw.bean.person;import Com.lw.bean.schoolinfo;public class Jsonadapter extends Baseadapter {private List<Person > list;private Context context;private layoutinflater inflater;private Handler Handler = new Handler ();p ublic Jsonadap ter (Context context) {This.context = Context;inflater = Layoutinflater.from (context);} Public Jsonadapter (list<person> List, Context context) {this.list = List;this.context = Context;inflater = Layoutin Flater.from (context);} /** * Set data, data is parsed from the server * @param list */public void SetData (list<person> list) {this.list = list;} @Overridepublic int GetCount () {return list.size ();} @Overridepublic Object getItem (int position) {return list.get (position);} @Overridepublic long getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = = null) {Convertview = inflater.inflate (R.layout.item, null); holder = new Viewholder (Convertview); Convertview.settag ( Holder);} else {holder = (Viewholder) Convertview.gettag ();} /*** * Item data is derived from SetData, */person person = list.get (position) in Jsonthread handler operation; Holder.name.setText ( Person.getname ()); Holder.age.setText (Person.getage () + ""); List<schoolinfo> SCS = Person.getschoolinfo (); Holder.school1.setText (Scs.get (0). GetName ()); Holder.school2.setText (Scs.get (1). GetName ());//Here The picture information, also need to open the sub-thread, to obtain, need to pass these 3 parameters of the new Httpimage (Holder.imageview, Person.geturl (), Handler). Start (); return convertview;} /** * Viewhodler not explained * */class Viewholder {private TextView name;private TextView age;private TextView school1;private Text View School2;private ImageView imageview;public viewholder (view view) {name = (TextView) view.findViewbyid (r.id.name); age = (TextView) View.findviewbyid (r.id.age); school1 = (TextView) View.findviewbyid (r.id.school1 ); school2 = (TextView) View.findviewbyid (r.id.school2); ImageView = (ImageView) View.findviewbyid (R.id.imageview);}}}
The next picture gets the thread
Httpimage
Package Com.lw.http01;import Java.io.ioexception;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.protocolexception;import Java.net.url;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.handler;import Android.widget.imageview;public class Httpimage extends Thread {/** * ImageView is the URL of the image that needs to be handler updated UI in a sub-thread * handle R is a */private ImageView imageview;private String url;private Handler handler;public httpimage (ImageView) for child threads and new UI operations ImageView, String URL, Handler Handler) {This.imageview = Imageview;this.url = Url;this.handler = Handler;} @Overridepublic void Run () {try {/** * = Jsonthread operation, the parameters of the series */url httpurl = new URL (URL); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); conn.setreadtimeout (5000); Conn.setrequestmethod ("get");//Such a way can also get a picture decodestreamfinal Bitmap Bitmap = Bitmapfactory.decodestream ( Conn.getinputstream ()); Handler.post (new Runnable () {@Overridepublic void Run () {//Sub-thread directlyUpdate interface Imageview.setimagebitmap (bitmap);}});} catch (Malformedurlexception e) {e.printstacktrace ()} catch (Protocolexception e) {//TODO auto-generated catch BLOCKE.P Rintstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JSON get, Parse case demo