Android中解析JSON的效率要比XML高很多,建議在開發中,數據不是很復雜就用JSON傳輸數據
- public class VideoService {
- public List<Video> getJsonVieos() throws IOException, JSONException{
- String path = "http://111.14.19.37:8080/vidoe/video/list.do?format=json";
- URL url = new URL(path);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5 * 1000);
- conn.setRequestMethod("GET");
- InputStream is = conn.getInputStream();
- byte[] data = InputStreamUtil.getByteArray(is);//用自己寫的工具類把流轉成byte數組
- String json = new String(data);
- JSONArray array = new JSONArray(json);
- List<Video> videos = new ArrayList<Video>();
- for(int i = 0; i<array.length(); i++){
- JSONObject jo = array.getJSONObject(i);
- int id = jo.getInt("id");
- String title = jo.getString("title");
- int timelength = jo.getInt("timelength");
- videos.add(new Video(id, title, timelength));
- }
- return videos;
- }
- }