[英]Parse JSON array of objects from url Java
如何使用 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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.