[英]Parse JSON array of objects from url Java
How do I parse an array of JSON objects from an external URL with the Java application?如何使用 Java 应用程序解析来自外部 URL 的 JSON 对象数组? Here is an example of code, that I am using:这是我正在使用的代码示例:
URL connectionUrl = new URL(/*some url*/);
connection = (HttpURLConnection) connectionUrl.openConnection();
String postData = "/*some post data*/";
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(postData.length());
OutputStream outputStream = null;
outputStream = connection.getOutputStream();
outputStream.write(postData.getBytes());
if(connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String magicString = "", magicLine;
while((magicLine = bufferedReader.readLine()) != null) {
JSONArray jsonArr = new JSONArray(magicLine);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject currentEntity = jsonArr.getJSONObject(i);
}
}
return magicString;
And this one is the array of JSON objects, that gets echo'd out on some external URL:这个是 JSON 对象的数组,它在一些外部 URL 上得到回显:
[{"ID":"1","name":"test name","phone":"+37120000000","email":"test@cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"0"},{"ID":"2","name":"test name","phone":"+37120000000","email":"test@cream.camp","date":"2020-12-17","time":"18:50:00","people_num":"4","active":"1"}]
Unfortunately, the application fails with the following error:不幸的是,应用程序失败并出现以下错误:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONArray
You can create a POJO to hold JSON response.您可以创建一个 POJO 来保存 JSON 响应。 Use third-party jar such as Jackson.使用第三方 jar 如 Jackson。 Something like the following:类似于以下内容:
ObjectMapper mapper = new ObjectMapper();
try {
YourPOJO obj = mapper.readValue(new URL("http://jsonplaceholder.typicode.com/posts/7"), YourPOJO.class);
System.out.println(usrPost);
} catch (Exception e) {
e.printStackTrace();
}
Refer to https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/参考https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.