2025-02-10

 

解析JSON的效率要比xml高很多,建議在開發中,數據不是很復雜就用JSON傳輸數據

 

public class VideoService { 

    public List<Video> getJsonVieos() throws IOException, JSONException{ 

        String path = "https://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; 

    } 

}   

摘自:com360 博客

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *