这可能是一个愚蠢的问题,但是在Java中从URL读取和解析JSON的最简单的方法是什么?

在Groovy中,这只是几行代码的问题。我发现Java示例长得离谱(并且有巨大的异常处理块)。

我所要做的就是阅读这个链接的内容。


当前回答

Oracle文档描述了如何操作

一个HttpRequest被构建,然后 由HttpClient发送给URL

只需几行代码,通过使用Java类库。把这段代码放到你的main方法中:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://example.com/"))
      .build();
client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

响应由JSON对象{…},并可在您的申请中进一步处理。 在这里我把它打印到控制台,只是为了确认它是有效的:

System.out.println(request);

这可用于Java版本11+

其他回答

我不确定这是否有效,但这是一种可能的方法:

使用url. openstream()从url读取json,并将内容读入字符串。

用这个字符串构造一个JSON对象(更多信息请访问json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.

我想在这里添加一个更新的答案,因为最近对JDK的更新使读取HTTP URL的内容变得更容易了。 正如其他人所说,您仍然需要使用JSON库来进行解析,因为JDK目前还不包含JSON库。 下面是一些最常用的Java JSON库:

组织。杰伦 FasterXML Jackson 格森

要从URL检索JSON,这似乎是严格使用JDK类的最简单方法(但对于大型有效负载,可能不是您想要做的事情),Java 9介绍了:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html#readAllBytes()

try(java.io.InputStream is = new java.net.URL("https://graph.facebook.com/me").openStream()) {
    String contents = new String(is.readAllBytes());
}

例如,使用GSON库解析JSON

com.google.gson.JsonElement element = com.google.gson.JsonParser.parseString(contents); //from 'com.google.code.gson:gson:2.8.6'

我发现这是迄今为止最简单的方法。

使用这个方法:

public static String getJSON(String url) {
        HttpsURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpsURLConnection) u.openConnection();

            con.connect();


            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            return sb.toString();


        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (con != null) {
                try {
                    con.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

像这样使用它:

String json = getJSON(url);
JSONObject obj;
   try {
         obj = new JSONObject(json);
         JSONArray results_arr = obj.getJSONArray("results");
         final int n = results_arr.length();
            for (int i = 0; i < n; ++i) {
                // get the place id of each object in JSON (Google Search API)
                String place_id = results_arr.getJSONObject(i).getString("place_id");
            }


   }

Oracle文档描述了如何操作

一个HttpRequest被构建,然后 由HttpClient发送给URL

只需几行代码,通过使用Java类库。把这段代码放到你的main方法中:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://example.com/"))
      .build();
client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

响应由JSON对象{…},并可在您的申请中进一步处理。 在这里我把它打印到控制台,只是为了确认它是有效的:

System.out.println(request);

这可用于Java版本11+

最简单的方法: 使用gson,谷歌自己的goto json库。https://code.google.com/p/google-gson/

这是一个样品。我到这个免费的地理定位器网站,解析json,显示邮政编码。(只要把这些东西放在主方法中测试就可以了)

    String sURL = "http://freegeoip.net/json/"; //just a string

    // Connect to the URL using java's native library
    URL url = new URL(sURL);
    URLConnection request = url.openConnection();
    request.connect();

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
    String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode