[英]Read json data from url using java
我读过一些答案,比如
但它不能工作。
好的,这是我的代码
package day1;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class MainGet {
public static void main(String[] args) {
try {
URL url = new URL("https://api.covid19api.com/summary");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
//Getting the response code
int responsecode = conn.getResponseCode();
if (responsecode != 200) {
throw new RuntimeException("HttpResponseCode: " + responsecode);
} else {
String inline = "";
Scanner scanner = new Scanner(url.openStream());
//Write all the JSON data into a string using a scanner
while (scanner.hasNext()) {
inline += scanner.nextLine();
}
//Close the scanner
scanner.close();
//Using the JSON simple library parse the string into a json object
JSONParser parse = new JSONParser();
JSONObject data_obj = (JSONObject) parse.parse(inline);
//Get the required object from the above created object
JSONObject obj = (JSONObject) data_obj.get("Global");
//Get the required data using its key
System.out.println(obj.get("TotalRecovered"));
JSONArray arr = (JSONArray) data_obj.get("Countries");
for (int i = 0; i < arr.size(); i++) {
JSONObject new_obj = (JSONObject) arr.get(i);
if (new_obj.get("Slug").equals("albania")) {
System.out.println("Total Recovered: " + new_obj.get("TotalRecovered"));
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我想要一个可以在 eclipse 中运行的示例。 我已经安装 gson 并且我使用 jdk11。
here is my url: https://ws.yunlin.gov.tw/001/Upload/539/opendata/15369/1096/61b84dbc-5fe5-4569-8b94-4eebf1deef71.json
我想把它读入 java
非常感谢
我想我已经将 org.json 添加到路径中,但仍然有错误
您没有提供错误描述。 假设它是 JSON 解析错误。 URL 不返回 JSONObject,而是返回 JSONArray。
这几乎是复制和粘贴解决方案。
https://mkyong.com/java/gson-how-to-parse-json-arrays-an-array-of-arrays/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.