JSON 解析 方法
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();
}