This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?
In Groovy, it\
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");
}
}