下面是json的用法代码演示:
/**
* 下载tuijian.json
*/
private String initJSON() {
try {
URL url = new URL(Constant.TUIJIAN_JSON);
InputStream is = url.openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = is.read(buffer))) {
baos.write(buffer, 0, len);
}
return baos.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 解析json
*
* @param json
*/
private ArrayList<AlbumInfo> parseJSON(String json) {
ArrayList<AlbumInfo> albumInfos = new ArrayList<AlbumInfo>();
try {
JSONArray jsonArr = new JSONArray(json);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
AlbumInfo info = new AlbumInfo();
info.id = jsonObj.getInt("id");
info.name = jsonObj.getString("name");
info.url = jsonObj.getString("url");
info.p_w_picpath = jsonObj.getString("p_w_picpath");
info.rating = jsonObj.getString("rating");
info.artist_name = jsonObj.getString("artist_name");
albumInfos.add(info);
}
return albumInfos;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;