Android data is converted to Json to use json data on the client and client.
(1) first create the service that generates raw data, VideoNewsServiceBean, which is an interface implementation class. The interface functions are as follows:
Public interface VideoNewsService {/*** get the latest video information * @ return */public List
GetLastNews ();}
News class
Public class News {private Integer id; private String title; private Integer timelength; public News (Integer id, String title, Integer timelength) {this. id = id; this. title = title; this. timelength = timelength;} // get/set Method}
Interface implementation class: generate some false data
Public class VideoNewsServiceBean implements VideoNewsService {public List
GetLastNews () {List
Newes = new ArrayList
(); Newes. add (new News (90, "Pleasant goat and Big Wolf", 78); newes. add (new News (10, "real-time helicopter rescue drills in the East China Sea", 28); newes. add (new News (56, "Cameroon VS Holland", 70); return newes ;}}
(2) return data to the client through servlet: ListServlet. java
Public class ListServlet extends HttpServlet {private static final long serialVersionUID = 1L; private VideoNewsService service = new VideoNewsServiceBean (); protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {List
Videos = service. getLastNews (); // [{id: 56, title: "xxxxx", timelength: 90}, {id: 16, title: "xbbx", timelength: 20}] StringBuilder builder = new StringBuilder (); // append the data to the json format builder. 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 the last multi-character builder. deleteCharAt (builder. length ()-1); builder. append (']'); // sets the data in the request domain to jump to the jsp page when the client requests the servlet. The actual request is the jsp page request. setAttribute ("json", builder. toString (); request. getRequestDispatcher ("/WEB-INF/page/jsonvideonews. jsp "). forward (request, response );}}
(3) When the client initiates a request through servlet, the jsp page data can be returned after the jump (the el expression is used, because the json data is of the String type, contentType = "text/plain; charset = UTF-8 ")
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
(4) retrieve data from the client
The first step is to create a News class, which is omitted here.
Create a service for obtaining Json, VideoNewsService. java
Public class VideoNewsService {/*** get the latest video information * @ return * @ throws Exception */public static List
GetJSONLastNews () throws Exception {String path = "server request servlet address"; URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); if (conn. getResponseCode () = 200) {InputStream inStream = conn. getInputStream (); return parseJSON (inStream);} return null;}/*** parse JSON data * @ param inStream * @ return */private static List
ParseJSON (InputStream inStream) throws Exception {List
Newses = new ArrayList
(); Byte [] data = StreamTool. read (inStream); String json = new String (data); // because data is repeated in the form of arrays, JSONArray array = new JSONArray (json ); for (int I = 0; I <array. length (); I ++) {JSONObject jsonObject = array. getJSONObject (I); News news = new News (jsonObject. getInt ("id"), jsonObject. getString ("title"), jsonObject. getInt ("timelength"); newses. add (news) ;}return newses ;}}
A tool class StreamTool. java is used here to convert the input stream into byte data and return
Public class StreamTool {/*** read input stream data */public static byte [] read (InputStream inStream) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = inStream. read (buffer ))! =-1) {outStream. write (buffer, 0, len);} inStream. close (); return outStream. toByteArray ();}
Then, you can use the data on the specific interface: (set the value for a listview)
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
Videos = VideoNewsService. getJSONLastNews (); // you need to change it to your local Http Request Path. // List used here
> You can put the data into the hashmap and then the list in the List set.
> Data = new ArrayList
> (); For (News news: videos) {HashMap
Item = new HashMap
(); 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 SimpleAdapter adapter = new SimpleAdapter (this, data, R. layout. item, new String [] {"title", "timelength"}, new int [] {R. id. title, R. id. timelength}); listView. setAdapter (adapter);} catch (Exception e) {e. printStackTrace ();}}}
The json data generation client has completed the json data operation!