Android中获取JSON

来源:互联网 发布:轰炸手机号码软件 编辑:程序博客网 时间:2024/06/07 17:45
  1. /**    
  2.      * 数据形式:{"id":1,"isNo":false,"data":[{"id":1,"name":"张三"},{"id":2,"name":"李四"},{"id":2,"name":"王五"}]}    
  3.      */    
  4.     public static List<Map<String, String>> getJSONObject(String path) throws Exception {     
  5.         List<Map<String, String>> list = new ArrayList<Map<String, String>>();     
  6.         Map<String, String> map = null;     
  7.         URL url = new URL(path);    
  8. // HttpURLConnection可以从网络中获取数据.  
  9.         HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
  10. // 设置超时时间    
  11.         conn.setConnectTimeout(5 * 1000);
  12.         conn.setRequestMethod("GET");//这个应该都知道是干嘛的,默认是GET
  13.         if (conn.getResponseCode() == 200) {// 判断请求码,不是200则为请求失败   
  14.             InputStream is = conn.getInputStream(); // 获取输入流     
  15.             byte[] data = readStream(is);       
  16.             String json = new String(data);    
  17.                         
  18.             JSONObject jsonObject=new JSONObject(json);     //返回的数据形式是一个Object类型     
  19.             int total=jsonObject.getInt("id");     
  20.             Boolean success=jsonObject.getBoolean("isNo");      
  21.                  
  22.             JSONArray jsonArray = jsonObject.getJSONArray("data");//用getJSONArray获取数组     
  23.             for (int i = 0; i < jsonArray.length(); i++) {     
  24.                 JSONObject item = jsonArray.getJSONObject(i);     
  25.                 int id = item.getInt("id");      
  26.                 String name = item.getString("name");     
  27.     
  28.                 map = new HashMap<String, String>();   
  29.                 map.put("id", id + "");     
  30.                 map.put("name", name);     
  31.                 list.add(map);     
  32.             }     
  33.         }              
  34.     
  35.         return list;     
  36.     }     
此为{"id":1,"isNo":false,"data":[{"id":1,"name":"张三"},{"id":2,"name":"李四"},{"id":2,"name":"王五"}]} 类型的JSON,其他类型的都可以通过此方法获得,转换时举一反三就可以了。
0 0
原创粉丝点击