//JSON数据格式 /* [{id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, {id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, {id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, {id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, {id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, {id:1,title:"实拍奥巴马国宴秀中国谚语 主菜烤牛排",timelength:90}, ] */ JSON 解析 方法 /** * 获取网络的最新视频资讯 JSON * @return * @throws Exception */ public static List<Video> getJSONLastVideos() throws Exception { String path="http://192.168.1.168:8080/video/data=json"; URL url=new URL(path); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(1000*5); if(conn.getResponseCode()==200) { InputStream inputStream=conn.getInputStream(); return parseJSON(inputStream); } return null; } /** * 解析JSON 数据 * @param inputStream * @return * @throws Exception */ private static List<Video> parseJSON(InputStream inputStream) { List<Video> videos=new ArrayList<Video>(); try { byte[] data=readStream(inputStream); String json=new String(data); JSONArray jsonArray=new JSONArray(json); for(int i=0;i<jsonArray.length();i++) { JSONObject jsonObject=jsonArray.getJSONObject(i); Video video=new Video(jsonObject.getInt("id"), jsonObject.getString("title"), jsonObject.getInt("timelength")); videos.add(video); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return videos; } /** * 读取流中的数据 * @param inStream * @return * @throws Exception */ public static byte[] readStream(InputStream inputStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inputStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); } outStream.close(); inputStream.close(); return outStream.toByteArray(); }