【发布时间】:2018-12-20 11:44:43
【问题描述】:
我正在尝试获取 JSON 响应,它采用数组格式。这个 JSON 响应我想转换成 Java 数组。
这是数组:
[{"id":"1","Name":"Daniyal"},
{"id":"2","Name":"Aslam"},
{"id":"3","Name":"Kamal"},
{"id":"4","Name":"Asghar"},
{"id":"5","Name":"Jamal"},
{"id":"6","Name":"Suraj"},
{"id":"7","Name":"Mujji"}]
这是代码:
try {
URL urlForGetRequest = new URL("http://xenzet.com/ds/ds.php?");
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");
conection.setRequestProperty("userId", "a1bcdef"); // set userId its a sample here
int responseCode = conection.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + urlForGetRequest);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
System.out.println(response.toString());
//Read JSON response and print
JSONArray myResponse = new JSONArray(response.toString());
System.out.println("result after Reading JSON Response");
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
【问题讨论】:
-
正是您在这里面临的问题。有什么例外吗?
-
我想收到以上所有数据,然后我会将名称放入数组中,暂时不使用 id 但仍然派上用场,我收到 404 错误