Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發——獲取網絡資源之json數據

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

編輯:關於Android編程

一、項目背景 在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有所不同,只要熟悉一下即可。      
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved