- /**
- * 数据形式:{"id":1,"isNo":false,"data":[{"id":1,"name":"张三"},{"id":2,"name":"李四"},{"id":2,"name":"王五"}]}
- */
- public static List<Map<String, String>> getJSONObject(String path) throws Exception {
- List<Map<String, String>> list = new ArrayList<Map<String, String>>();
- Map<String, String> map = null;
- URL url = new URL(path);
- // HttpURLConnection可以从网络中获取数据.
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- // 设置超时时间
- conn.setConnectTimeout(5 * 1000);
- conn.setRequestMethod("GET");//这个应该都知道是干嘛的,默认是GET
- if (conn.getResponseCode() == 200) {// 判断请求码,不是200则为请求失败
- InputStream is = conn.getInputStream(); // 获取输入流
- byte[] data = readStream(is);
- String json = new String(data);
- JSONObject jsonObject=new JSONObject(json); //返回的数据形式是一个Object类型
- int total=jsonObject.getInt("id");
- Boolean success=jsonObject.getBoolean("isNo");
- JSONArray jsonArray = jsonObject.getJSONArray("data");//用getJSONArray获取数组
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject item = jsonArray.getJSONObject(i);
- int id = item.getInt("id");
- String name = item.getString("name");
- map = new HashMap<String, String>();
- map.put("id", id + "");
- map.put("name", name);
- list.add(map);
- }
- }
- return list;
- }
此为{"id":1,"isNo":false,"data":[{"id":1,"name":"张三"},{"id":2,"name":"李四"},{"id":2,"name":"王五"}]} 类型的JSON,其他类型的都可以通过此方法获得,转换时举一反三就可以了。