Android解析JSON

来源:互联网 发布:微小宝mac版 编辑:程序博客网 时间:2024/05/22 05:16
Android解析json格式的性能比解析XML要高.所以当Android应用请求网络资源时,WEB服务器不返回XML数据,而是json格式的数据.如视频信息Video类的字段为:private Integer id;private String title;private Integer timelength;第一部分:Android客户端(1)Android客户端发送请求public static List<Video> getJSONVideos() throws Exception{String path="http://192.168.1.120:8080/androidStruts/video.do?format=json";URL url=new URL(path);HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(5000);httpURLConnection.setRequestMethod("GET");InputStream inputStream=httpURLConnection.getInputStream();if(httpURLConnection.getResponseCode()==200){return parseJSON(inputStream);//parseJSON(InputStream inputStream)方法见下}return null;}(2)Android客户端解析JSON数据步骤:1 将服务器返回的字节数组转换为字符串2 将字符串数据转换为JSON数组——JSONArray jsonArray=new JSONArray(stringVideosData);3 遍历JSON数组,取出数组里的每个元素,其类型JSONObject为——JSONObject jsonObject=jsonArray.getJSONObject(i);4 将每个JSONObject对象的对应值取出来,再填充到对应的JavaBean里面public static List<Video> parseJSON(InputStream inputStream) throws Exception{List<Video> videos=new ArrayList<Video>();byte [] byteVideosData=GetResource.readResource(inputStream);//readResource(InputStream inputStream)方法见下String  stringVideosData=new String(byteVideosData);JSONArray jsonArray=new JSONArray(stringVideosData);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);}return videos;}public class GetResource {    public static byte[] readResource(InputStream inputStream) throws Exception{    ByteArrayOutputStream outputStream=new ByteArrayOutputStream();    byte [] array=new byte[1024];    int len=0;    while( (len=inputStream.read(array))!=-1){       outputStream.write(array,0,len);    }    inputStream.close();    outputStream.close();        return outputStream.toByteArray();    }}第二部分:WEB服务器当Android应用请求网络资源时,WEB服务器发现path中的参数format=json,于是生成JSON数据StringBuilder sbsbJson=new StringBuilder();sbJson.append('[');    for(Video video:videos){    sbJson.append('{');    sbJson.append("id:").append(video.getId()).append(',');    sbJson.append("title:").append(video.getTitle()).append(',');    sbJson.append("timelength:").append(video.getTimelength());    sbJson.append('}').append(',');    }sbJson.deleteCharAt(sbJson.length()-1);//去掉最后一个多余的逗号sbJson.append(']');最终得到:[{id:1,title:犀利哥视频,timelength:45},{id:2,title:福原爱视频,timelength:55},{id:3,title:陈绮贞视频,timelength:65}]Android客户端读到的就是这些JSON格式的数据

原创粉丝点击