Simplest way to read json from a URL in java

后端 未结 11 1082
情书的邮戳
情书的邮戳 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条回答
  •  既然无缘
    2020-11-22 05:13

    Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

    package so4308554;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URL;
    import java.nio.charset.Charset;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class JsonReader {
    
      private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
          sb.append((char) cp);
        }
        return sb.toString();
      }
    
      public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
          BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
          String jsonText = readAll(rd);
          JSONObject json = new JSONObject(jsonText);
          return json;
        } finally {
          is.close();
        }
      }
    
      public static void main(String[] args) throws IOException, JSONException {
        JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
        System.out.println(json.toString());
        System.out.println(json.get("id"));
      }
    }
    

提交回复
热议问题