歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中解析服務器發過來的JSON數據

Android中解析服務器發過來的JSON數據

日期:2017/3/1 11:13:06   编辑:Linux編程
Android中解析JSON的效率要比XML高很多,建議在開發中,數據不是很復雜就用JSON傳輸數據
  1. public class VideoService {
  2. public List<Video> getJsonVieos() throws IOException, JSONException{
  3. String path = "http://111.14.19.37:8080/vidoe/video/list.do?format=json";
  4. URL url = new URL(path);
  5. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  6. conn.setConnectTimeout(5 * 1000);
  7. conn.setRequestMethod("GET");
  8. InputStream is = conn.getInputStream();
  9. byte[] data = InputStreamUtil.getByteArray(is);//用自己寫的工具類把流轉成byte數組
  10. String json = new String(data);
  11. JSONArray array = new JSONArray(json);
  12. List<Video> videos = new ArrayList<Video>();
  13. for(int i = 0; i<array.length(); i++){
  14. JSONObject jo = array.getJSONObject(i);
  15. int id = jo.getInt("id");
  16. String title = jo.getString("title");
  17. int timelength = jo.getInt("timelength");
  18. videos.add(new Video(id, title, timelength));
  19. }
  20. return videos;
  21. }
  22. }
Copyright © Linux教程網 All Rights Reserved