如何使用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
1条答案
按热度按时间qlfbtfca1#
您可以创建一个pojo来保存json响应。使用第三方jar,比如jackson,比如following:-
参考https://www.java2novice.com/java-json/jackson/jackson-client-read-from-api-url/