一、项目背景
在Android开发中有一项非常广泛的应用:Android项目获取另一个web项目的资源或者返回的数据。
本文获取web项目返回的JSON数据。Android应用解析JSON比XML性能要好,但有许多项目仍然采用的是XML。

 

二、实例代码

Web项目

 
  
  1. /**  
  2.  * 新闻业务类  
  3.  *   
  4.  * @author 徐越  
  5.  *   
  6.  */ 
  7. public class VideoNewsServiceImpl implements VideoNewsService  
  8. {  
  9.     public List<VideoNews> readNews()  
  10.     {  
  11.         List<VideoNews> lst = new ArrayList<VideoNews>();  
  12.         lst.add(new VideoNews(1"喜洋洋"20));  
  13.         lst.add(new VideoNews(2"变形金刚"10));  
  14.         lst.add(new VideoNews(3"功夫熊猫"20));  
  15.         return lst;  
  16.     }  
  17. }  
  18.  
  19. /**  
  20.  * 新闻Servlet  
  21.  *   
  22.  * @author 徐越  
  23.  *   
  24.  */ 
  25. public class ListServlet extends HttpServlet  
  26. {  
  27.     private static final long serialVersionUID = 1L;  
  28.     private VideoNewsService vs = new VideoNewsServiceImpl();  
  29.  
  30.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  31.     {  
  32.         doPost(request, response);  
  33.     }  
  34.  
  35.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  36.     {  
  37.         List<VideoNews> news = vs.readNews();  
  38.         JSONArray jsonarr = JSONArray.fromObject(news);  
  39.         response.setCharacterEncoding("UTF-8");  
  40.         response.setContentType("text/plain;charset=UTF-8");  
  41.         response.setHeader("Pragma""No-cache");  
  42.         response.setHeader("Cache-Control""no-cache");  
  43.         response.setDateHeader("Expires"0);  
  44.         response.getWriter().print(jsonarr);  
  45.     }  

Android项目

 
  
  1. public class VideoNewsServiceImpl implements VideoNewsService  
  2. {  
  3.  
  4.     /**  
  5.      * 获取最新视频资讯,从JSON文件中,解析效率高  
  6.      *   
  7.      * @return  
  8.      * @throws Exception  
  9.      */ 
  10.     public List<VideoNews> getNewsFromJson() throws Exception  
  11.     {  
  12.         List<VideoNews> lst = new ArrayList<VideoNews>();  
  13.         String path = "http://xxx.xxx.xxx.xxx:8080/web/ListServlet";  
  14.         URL url = new URL(path);  
  15.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  16.         conn.setReadTimeout(5000);  
  17.         conn.setRequestMethod("GET");  
  18.         if (200 == conn.getResponseCode())  
  19.         {  
  20.             InputStream instream = conn.getInputStream();  
  21.             lst = parseJSON(instream);  
  22.         }  
  23.         return lst;  
  24.     }  
  25.  
  26.     /**  
  27.      * 解析JSON  
  28.      */ 
  29.     private List<VideoNews> parseJSON(InputStream instream) throws Exception  
  30.     {  
  31.         List<VideoNews> lst = new ArrayList<VideoNews>();  
  32.         byte[] data = IOUtils.read(instream);  
  33.         String jsonStr = new String(data);  
  34.         JSONArray array = new JSONArray(jsonStr);  
  35.         for (int i = 0; i < array.length(); i++)  
  36.         {  
  37.             JSONObject jsonObj = (JSONObject) array.getJSONObject(i);  
  38.             VideoNews v = new VideoNews(jsonObj.getInt("id"),   
  39.                     jsonObj.getString("title"), jsonObj.getInt("timeLength"));  
  40.             lst.add(v);  
  41.         }  
  42.         return lst;  
  43.     }  
  44. }  
  45.  
  46. /**  
  47.  * IO操作工具类  
  48.  *   
  49.  * @author 徐越  
  50.  *   
  51.  */ 
  52. public class IOUtils  
  53. {  
  54.     /**  
  55.      * 读取输入流为byte[]数组  
  56.      */ 
  57.     public static byte[] read(InputStream instream) throws IOException  
  58.     {  
  59.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  60.         byte[] buffer = new byte[1024];  
  61.         int len = 0;  
  62.         while ((len = instream.read(buffer)) != -1)  
  63.         {  
  64.             bos.write(buffer, 0, len);  
  65.         }  
  66.         return bos.toByteArray();  
  67.     }  

需要指出的是
在web项目中我采用的是net.sf.json下的类对JSON进行解析,而Android项目中默认自带的JSON包是org.json。API有所不同,只要熟悉一下即可。