Android開發18——獲取網絡資源之json數據

本文出自 “IT徐胖子的專欄” 博客,請務必保留此出處http://woshixy.blog.51cto.com/5637578/1088074


一、項目背景
在Android開發中有一項非常廣泛的應用:Android項目獲取另一個web項目的資源或者返回的數據。
本文獲取web項目返回的JSON數據。Android應用解析JSON比XML性能要好,但有許多項目仍然採用的是XML。


二、實例代碼

Web項目

  1. /**

  2. * 新聞業務類

  3. *  

  4. * @author 徐越

  5. *  

  6. */

  7. publicclass 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. * 新聞Servlet

  20. *  

  21. * @author 徐越

  22. *  

  23. */

  24. publicclass ListServlet extends HttpServlet  

  25. {  

  26. privatestaticfinallong serialVersionUID = 1L;  

  27. private VideoNewsService vs = new VideoNewsServiceImpl();  

  28. protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  

  29.    {  

  30.        doPost(request, response);  

  31.    }  

  32. protectedvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  

  33.    {  

  34.        List<VideoNews> news = vs.readNews();  

  35.        JSONArray jsonarr = JSONArray.fromObject(news);  

  36.        response.setCharacterEncoding("UTF-8");  

  37.        response.setContentType("text/plain;charset=UTF-8");  

  38.        response.setHeader("Pragma", "No-cache");  

  39.        response.setHeader("Cache-Control", "no-cache");  

  40.        response.setDateHeader("Expires", 0);  

  41.        response.getWriter().print(jsonarr);  

  42.    }  

  43. }

Android項目

  1. publicclass VideoNewsServiceImpl implements VideoNewsService  

  2. {  

  3. /**

  4.     * 獲取最新視頻資訊,從JSON文件中,解析效率高

  5.     *  

  6.     * @return

  7.     * @throws Exception

  8.     */

  9. public List<VideoNews> getNewsFromJson() throws Exception  

  10.    {  

  11.        List<VideoNews> lst = new ArrayList<VideoNews>();  

  12.        String path = "http://xxx.xxx.xxx.xxx:8080/web/ListServlet";  

  13.        URL url = new URL(path);  

  14.        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  

  15.        conn.setReadTimeout(5000);  

  16.        conn.setRequestMethod("GET");  

  17. if (200 == conn.getResponseCode())  

  18.        {  

  19.            InputStream instream = conn.getInputStream();  

  20.            lst = parseJSON(instream);  

  21.        }  

  22. return lst;  

  23.    }  

  24. /**

  25.     * 解析JSON

  26.     */

  27. private List<VideoNews> parseJSON(InputStream instream) throws Exception  

  28.    {  

  29.        List<VideoNews> lst = new ArrayList<VideoNews>();  

  30. byte[] data = IOUtils.read(instream);  

  31.        String jsonStr = new String(data);  

  32.        JSONArray array = new JSONArray(jsonStr);  

  33. for (int i = 0; i < array.length(); i++)  

  34.        {  

  35.            JSONObject jsonObj = (JSONObject) array.getJSONObject(i);  

  36.            VideoNews v = new VideoNews(jsonObj.getInt("id"),  

  37.                    jsonObj.getString("title"), jsonObj.getInt("timeLength"));  

  38.            lst.add(v);  

  39.        }  

  40. return lst;  

  41.    }  

  42. }  

  43. /**

  44. * IO操作工具類

  45. *  

  46. * @author 徐越

  47. *  

  48. */

  49. publicclass IOUtils  

  50. {  

  51. /**

  52.     * 讀取輸入流爲byte[]數組

  53.     */

  54. publicstaticbyte[] read(InputStream instream) throws IOException  

  55.    {  

  56.        ByteArrayOutputStream bos = new ByteArrayOutputStream();  

  57. byte[] buffer = newbyte[1024];  

  58. int len = 0;  

  59. while ((len = instream.read(buffer)) != -1)  

  60.        {  

  61.            bos.write(buffer, 0, len);  

  62.        }  

  63. return bos.toByteArray();  

  64.    }  

  65. }

需要指出的是
在web項目中我採用的是net.sf.json下的類對JSON進行解析,而Android項目中默認自帶的JSON包是org.json。API有所不同,只要熟悉一下即可。


本文出自 “IT徐胖子的專欄” 博客,請務必保留此出處http://woshixy.blog.51cto.com/5637578/1088074


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章