java代码
- protected String getJsonString(String urlPath) throws Exception {
- URL url = new URL(urlPath);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.connect();
- InputStream inputStream = connection.getInputStream();
- //对应的字符编码转换
- Reader reader = new InputStreamReader(inputStream, "UTF-8");
- BufferedReader bufferedReader = new BufferedReader(reader);
- String str = null;
- StringBuffer sb = new StringBuffer();
- while ((str = bufferedReader.readLine()) != null) {
- sb.append(str);
- }
- reader.close();
- connection.disconnect();
- return sb.toString();
- }
xml代码
- {"FatherName":"Marry",
- "Childs":
- [
- {"Name":"A"},
- {"Name":"B"},
- {"Name":"C"},
- ]
- }
java代码
- public void jsonToObj(String jsonStr) throws Exception {
- Page page = new Page();
- JSONObject jsonObject = new JSONObject(jsonStr);
- String fatherName = jsonObject.getString("FatherName");
- JSONArray childs= jsonObject.getJSONArray("Childs");
- int length = childs.length();
- for (int i = 0; i < length; i++) {
- jsonObject = items.getJSONObject(i);
- String childName = jsonObject.getString("Name");
- }
- }