繁体   English   中英

从 url Java 中解析 JSON 对象数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM