Android開發——擷取網路資源之json資料

來源:互聯網
上載者:User

一、項目背景在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有所不同,只要熟悉一下即可。   

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.