Simplest way to read json from a URL in java

后端 未结 11 985
情书的邮戳
情书的邮戳 2020-11-22 04:15

This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it\

11条回答
  •  -上瘾入骨i
    2020-11-22 05:03

    I wanted to add an updated answer here since (somewhat) recent updates to the JDK have made it a bit easier to read the contents of an HTTP URL. Like others have said, you'll still need to use a JSON library to do the parsing, since the JDK doesn't currently contain one. Here are a few of the most commonly used JSON libraries for Java:

    • org.JSON
    • FasterXML Jackson
    • GSON

    To retrieve JSON from a URL, this seems to be the simplest way using strictly JDK classes (but probably not something you'd want to do for large payloads), Java 9 introduced: 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());
    }
    

    To parse the JSON using the GSON library, for example

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

提交回复
热议问题