日期:2014-05-16 浏览次数:20453 次
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; //获取解析的串,如下json串 public static String getJsonString(String urlPath) throws Exception { StringBuffer sb = new StringBuffer(); try { URL url = new URL(urlPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(50000); connection.connect(); InputStream inputStream = connection.getInputStream(); //对应的字符编码转换 Reader reader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(reader); String str = null; while ((str = bufferedReader.readLine()) != null) { sb.append(str); } reader.close(); connection.disconnect(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); System.out.println("连接超时。。。"); return "timeout"; } return sb.toString(); }
/** * 将上述json串转成对象列表 * @param jsonStr * @return * @throws Exception */ public static List jsonListToObjectList(String jsonStr) throws Exception { List<User> userList = new ArrayList<User>(); JSONObject jsonObject = new JSONObject(jsonStr); String response = jsonObject.getString("response"); String json = jsonObject.getString("result"); JSONObject jsonObject2 = new JSONObject(json); if(jsonStr.indexOf("userList") > -1){ String uList = jsonObject2.getString("userList"); if(null != uList){ // JSONObject jsonObject4 = new JSONObject(uList); JSONArray arry = jsonObject2.getJSONArray("userList"); for(int i=0;i<arry.length();i++){ JSONObject jsonObject5=(JSONObject)arry.get(i); String name=jsonObject5.getString("name"); String cgCount=jsonObject5.getString("cgCount"); User user = new User(); user.setName(name); user.setCgCount(Integer.parseInt(cgCount)); userList.add(user); } } } return userList; } public static Map jsonToObj(String jsonStr) throws Exception { JSONObject jsonObject = new JSONObject(jsonStr); String response = jsonObject.getString("response"); System.out.println("====================>response" + response); String json = jsonObject.getString("result"); System.out.println("json=============>" + jso