Get JSON data and parse
1 ImportJava.io.InputStream;2 Importjava.net.HttpURLConnection;3 ImportJava.net.URL;4 Importjava.util.ArrayList;5 Importjava.util.List;6 7 ImportOrg.json.JSONArray;8 ImportOrg.json.JSONObject;9 Ten Importcom.wangjialin.internet.json.domain.News; One ImportCom.wangjialin.internet.json.utils.StreamTool; A - Public classNewsservice { - the /** - * Get the latest video information - * @return - * @throwsException + */ - Public StaticList<news> Getjsonlastnews ()throwsexception{ + AString Path = "Http://192.168.1.103:8080/ServerForJSON/NewsListServlet"; atHttpURLConnection conn = (httpurlconnection)NewURL (path). OpenConnection (); -Conn.setconnecttimeout (5000); -Conn.setrequestmethod ("GET"); - - if(Conn.getresponsecode () = = 200){ -InputStream JSON =Conn.getinputstream (); in returnParsejson (JSON); - } to return NULL; + } - the Private StaticList<news> Parsejson (InputStream jsonstream)throwsexception{ * $list<news> list =NewArraylist<news>();Panax Notoginseng byte[] data =Streamtool.read (jsonstream); -String JSON =NewString (data); theJsonarray Jsonarray =NewJsonarray (JSON); + A for(inti = 0; I < jsonarray.length (); i++){ theJsonobject Jsonobject =Jsonarray.getjsonobject (i); + intid = jsonobject.getint ("id"); -String title = jsonobject.getstring ("title"); $ intTimelength = Jsonobject.getint ("Timelength"); $List.add (NewNews (ID, title, timelength)); - } - returnlist; the } -}
Streamtool
1 ImportJava.io.ByteArrayOutputStream;2 ImportJava.io.InputStream;3 4 Public classStreamtool {5 /**6 * Read data from the stream7 * @paraminstream8 * @return9 */Ten Public Static byte[] Read (InputStream instream)throwsexception{ One ABytearrayoutputstream OutputStream =NewBytearrayoutputstream (); - byte[] buffer =New byte[1024]; - intLen = 0; the - while(len = instream.read (buffer))! =-1){ -Outputstream.write (buffer, 0, Len); - } + - instream.close (); + returnOutputstream.tobytearray (); A } at}
Show
1 Public classMainactivityextendsActivity {2 /**Called when the activity is first created.*/3List<news>Newes;4listNULL;;5 String length;6 7 @Override8 Public voidonCreate (Bundle savedinstancestate) {9 Super. OnCreate (savedinstancestate);Ten One Setcontentview (r.layout.main); AListView ListView = (ListView) This. Findviewbyid (R.id.listview); - -Length = This. Getresources (). getString (r.string.length); the - Try{ -Newes =newsservice.getjsonlastnews (); -data =NewArraylist(); + for(News news:newes) { -hashmap<string, object> item =NewHashmap<string, object>(); +Item.put ("id", News.getid ()); AItem.put ("title", News.gettitle ()); atItem.put ("timelength", Length +news.gettimelength ()); - Data.add (item); - } - -Simpleadapter adapter =NewSimpleadapter ( This, - data, R.layout.item, in Newstring[]{"title", "Timelength"}, - New int[]{r.id.title, r.id.timelength} to ); + Listview.setadapter (adapter); -}Catch(Exception e) the { * e.printstacktrace (); $ };Panax Notoginseng } -}
Android development tool Class 25_getjson