我正在尝试获取JSON响应,该响应采用数组格式。我想在Java数组中转换此JSON响应。
这是数组:
[{"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();
}
答案 0 :(得分:0)
You can user JSONArray
e.g-
JSONArray jsonArray = new JSONArray(result.toString());
and afterwords you can parse that json arrray object using
ArrayList<String> listdata = new ArrayList<String>();
for(int n = 0; n < jsonArray.length(); n++)
{
JSONObject object = jsonArray.getJSONObject(n);
listdata.add(object.optString("n"));
}
return listdata;
答案 1 :(得分:0)
从该URL读取的问题是,显然需要“ User-Agent”请求标头。我设法通过以下代码读取了您的JSON:
import java.io.*;
import java.net.*;
public class JsonReader {
public static void main(String[] args) throws IOException {
JsonReader jsonReader = new JsonReader();
jsonReader.read("http://xenzet.com/ds/ds.php?");
}
public void read(String url) throws IOException {
URLConnection urlConnection = getUrlConnection(url);
String json;
try (InputStream inputStream = urlConnection.getInputStream()) {
json = readContent(inputStream);
}
System.out.println("JSON: " + json);
}
private String readContent(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
return sb.toString();
}
private URLConnection getUrlConnection(String url) throws IOException {
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
return urlConnection;
}
}