(1) First create the Service,videonewsservicebean that generates the original data, which is an implementation class of an interface, the functions of the interface are as follows:
publicinterface VideoNewsService { /** * 获取最新的视频资讯 * @return */ publicgetLastNews();}
News Category
publicclass News { private Integer id; private String title; private Integer timelength; publicNews(Integer id, String title, Integer timelength) { this.id = id; this.title = title; this.timelength = timelength; } //get/set方法}
Implementation classes for interfaces: generating some false data
Public class Videonewsservicebean implements videonewsservice { PublicList<news>getlastnews() {List<news> Newes =NewArraylist<news> (); Newes.add (NewNews ( -,"Pleasant goat and grey wolf complete", +)); Newes.add (NewNews (Ten,"Real shot ship helicopters in East China Sea Rescue Drill", -)); Newes.add (NewNews ( About,"Cameroon vs Holland", -));returnNewes; }}
(2) Returning data to the client via a servlet: Listservlet.java
Public class listservlet extends httpservlet { Private Static Final LongSerialversionuid =1LPrivateVideonewsservice Service =NewVideonewsservicebean ();protected void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doPost (request, response); }protected void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {list<news> videos = service.getlastnews ();//[{id:56,title: "xxxxx", Timelength:90},{id:16,title: "Xbbx", timelength:20}]StringBuilder Builder =NewStringBuilder ();//Append data to JSON formatBuilder.append (' ['); for(News News:videos) {Builder.append (' {'); Builder.append ("ID:"). Append (News.getid ()). Append (', '); Builder.append (" title:\ " "). Append (News.gettitle ()). Append ("\","); Builder.append ("Timelength:"). Append (News.gettimelength ()); Builder.append ("},"); }//Delete last multiple charactersBuilder.deletecharat (Builder.length ()-1); Builder.append ('] ');//Set the data in the request domain, jump to the JSP page when the client requests the servlet, and actually request the JSP pageRequest.setattribute ("JSON", builder.tostring ()); Request.getrequestdispatcher ("/web-inf/page/jsonvideonews.jsp"). Forward (request, response); }}
(3) When the client through the servlet request through the jump can return to the JSP page data (using the El expression, because the JSON data is a string type, so Contenttype= "text/plain; Charset=utf-8 ")
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
(4) Extracting data from the client
The same first step is still to create a news class, which omits
Create a Service,videonewsservice.java that gets JSON
Public class videonewsservice { /** * Get the latest video information * @return * @throws Exception */ Public StaticList<news>getjsonlastnews()throwsexception{String Path ="Server requests the address of the servlet"; URL url =NewURL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout ( the); Conn.setrequestmethod ("GET");if(Conn.getresponsecode () = = $) {InputStream instream = Conn.getinputstream ();returnParsejson (instream); }return NULL; }/** * Parse JSON data * @param instream * @return * * Private StaticList<news>Parsejson(InputStream instream)throwsexception{list<news> newses =NewArraylist<news> ();byte[] data = Streamtool.read (instream); String JSON =NewString (data);//Because the data is similar to the array in the form of repeated use of JsonarrayJsonarray array =NewJsonarray (JSON); for(inti =0; I < Array.Length (); i++) {Jsonobject jsonobject = Array.getjsonobject (i); News news =NewNews (Jsonobject.getint ("id"), Jsonobject.getstring ("title"), Jsonobject.getint ("Timelength")); Newses.add (news); }returnnewses; }}
Here, a tool class Streamtool.java is used to stream the input to a byte data return
Public class streamtool { /** * Read input stream data * / Public Static byte[]Read(InputStream instream)throwsException {Bytearrayoutputstream OutStream =NewBytearrayoutputstream ();byte[] buffer =New byte[1024x768];intLen =0; while(len = instream.read (buffer))! =-1) {outstream.write (buffer,0, Len); } instream.close ();returnOutstream.tobytearray (); }
You can then use the data in a specific interface: (Here is a ListView setting value)
Mainactivity.java
Public class mainactivity extends Activity { /** Called when the activity is first created. * / @Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); ListView ListView = (ListView) This. Findviewbyid (R.id.listview);Try{list<news> videos = videonewsservice.getjsonlastnews ();//need to modify the HTTP request path to your native computer //ListlistNewArraylist for(News News:videos) {hashmap<string, object> item =NewHashmap<string, object> (); Item.put ("id", News.getid ()); Item.put ("title", News.gettitle ()); Item.put ("Timelength", Getresources (). getString (r.string.timelength) + news.gettimelength () + getresources (). getString (R. String.min)); Data.add (item); }//Set the adapter for the ListViewSimpleadapter adapter =NewSimpleadapter ( This, data, R.layout.item,Newstring[]{"title","Timelength"},New int[]{r.id.title, r.id.timelength}]; Listview.setadapter (adapter); }Catch(Exception e) {E.printstacktrace (); } }}
The generated guest client to this JSON data uses the JSON data operation to complete!
Convert Android data to JSON to use JSON data for clients and clients