Android中获取JSON

  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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值