Java获取服务端Json数据

Java访问服务器端,下载服务器端Json数据

 

1.访问服务器地址,返回Json字符串

 

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();
	}

 

  返回格式

 

{"FatherName":"Marry",
    "Childs":
    [
        {"Name":"A"},
        {"Name":"B"},
        {"Name":"C"},
    ]
}
 

 2.解析

 

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");
		}
	}
 

 

 

你可能感兴趣的:(Java)