解析url Java中的对象的JSON数组



如何使用Java应用程序从外部URL解析JSON对象数组?以下是我正在使用的代码示例:

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;

这个是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"}]

不幸的是,应用程序失败,出现以下错误:

org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONArray

您可以创建一个POJO来保存JSON响应。使用第三方jar,如Jackson。类似以下内容:

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

请参阅https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/

最新更新