Simplest way to read json from a URL in java

后端 未结 11 929
情书的邮戳
情书的邮戳 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:03

    I have found this to be the easiest way by far.

    Use this method:

    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;
        }
    

    And use it like this:

    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");
                }
    
    
       }
    

提交回复
热议问题