一、項目背景在Android開發中有一項非常廣泛的應用:Android項目擷取另一個web項目的資源或者返回的資料。 本文擷取web項目返回的JSON資料。Android應用解析JSON比XML效能要好,但有許多項目仍然採用的是XML。 二、執行個體代碼 Web項目 [java] /** * 新聞業務類 * * @author 徐越 * */ public class VideoNewsServiceImpl implements VideoNewsService { public List<VideoNews> readNews() { List<VideoNews> lst = new ArrayList<VideoNews>(); lst.add(new VideoNews(1, "喜洋洋", 20)); lst.add(new VideoNews(2, "變形金剛", 10)); lst.add(new VideoNews(3, "功夫熊貓", 20)); return lst; } } /** * 新聞Servlet * * @author 徐越 * */ public class ListServlet extends HttpServlet { private static final long serialVersionUID = 1L; private VideoNewsService vs = new VideoNewsServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<VideoNews> news = vs.readNews(); JSONArray jsonarr = JSONArray.fromObject(news); response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain;charset=UTF-8"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.getWriter().print(jsonarr); } } /** * 新聞業務類 * * @author 徐越 * */public class VideoNewsServiceImpl implements VideoNewsService{public List<VideoNews> readNews(){List<VideoNews> lst = new ArrayList<VideoNews>();lst.add(new VideoNews(1, "喜洋洋", 20));lst.add(new VideoNews(2, "變形金剛", 10));lst.add(new VideoNews(3, "功夫熊貓", 20));return lst;}} /** * 新聞Servlet * * @author 徐越 * */public class ListServlet extends HttpServlet{private static final long serialVersionUID = 1L;private VideoNewsService vs = new VideoNewsServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{doPost(request, response);} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{List<VideoNews> news = vs.readNews();JSONArray jsonarr = JSONArray.fromObject(news);response.setCharacterEncoding("UTF-8");response.setContentType("text/plain;charset=UTF-8");response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);response.getWriter().print(jsonarr);}} Android項目 [java] view plaincopyprint?public class VideoNewsServiceImpl implements VideoNewsService { /** * 擷取最新視頻資訊,從JSON檔案中,解析效率高 * * @return * @throws Exception */ public List<VideoNews> getNewsFromJson() throws Exception { List<VideoNews> lst = new ArrayList<VideoNews>(); String path = "http://xxx.xxx.xxx.xxx:8080/web/ListServlet"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); if (200 == conn.getResponseCode()) { InputStream instream = conn.getInputStream(); lst = parseJSON(instream); } return lst; } /** * 解析JSON */ private List<VideoNews> parseJSON(InputStream instream) throws Exception { List<VideoNews> lst = new ArrayList<VideoNews>(); byte[] data = IOUtils.read(instream); String jsonStr = new String(data); JSONArray array = new JSONArray(jsonStr); for (int i = 0; i < array.length(); i++) { JSONObject jsonObj = (JSONObject) array.getJSONObject(i); VideoNews v = new VideoNews(jsonObj.getInt("id"), jsonObj.getString("title"), jsonObj.getInt("timeLength")); lst.add(v); } return lst; } } /** * IO操作工具類 * * @author 徐越 * */ public class IOUtils { /** * 讀取輸入資料流為byte[]數組 */ public static byte[] read(InputStream instream) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = instream.read(buffer)) != -1) { bos.write(buffer, 0, len); } return bos.toByteArray(); } } public class VideoNewsServiceImpl implements VideoNewsService{ /*** 擷取最新視頻資訊,從JSON檔案中,解析效率高* * @return* @throws Exception*/public List<VideoNews> getNewsFromJson() throws Exception{List<VideoNews> lst = new ArrayList<VideoNews>();String path = "http://xxx.xxx.xxx.xxx:8080/web/ListServlet";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(5000);conn.setRequestMethod("GET");if (200 == conn.getResponseCode()){InputStream instream = conn.getInputStream();lst = parseJSON(instream);}return lst;} /*** 解析JSON*/private List<VideoNews> parseJSON(InputStream instream) throws Exception{List<VideoNews> lst = new ArrayList<VideoNews>();byte[] data = IOUtils.read(instream);String jsonStr = new String(data);JSONArray array = new JSONArray(jsonStr);for (int i = 0; i < array.length(); i++){JSONObject jsonObj = (JSONObject) array.getJSONObject(i);VideoNews v = new VideoNews(jsonObj.getInt("id"), jsonObj.getString("title"), jsonObj.getInt("timeLength"));lst.add(v);}return lst;}} /** * IO操作工具類 * * @author 徐越 * */public class IOUtils{/*** 讀取輸入資料流為byte[]數組*/public static byte[] read(InputStream instream) throws IOException{ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = instream.read(buffer)) != -1){bos.write(buffer, 0, len);}return bos.toByteArray();}}需要指出的是 在web項目中我採用的是net.sf.json下的類對JSON進行解析,而Android項目中預設內建的JSON包是org.json。API有所不同,只要熟悉一下即可。