Get JSON in Java

Java JSON

Read an object

public static JSONObject readObjectFromUrl(URL url) throws IOException, JSONException { InputStream is = url.openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); return new JSONObject(jsonText); } finally { is.close(); } } 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(); }

Read an arry of objects

public static JSONArray readArrayFromUrl(URL url) throws IOException, JSONException { InputStream is = url.openStream(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); String jsonText = readAll(rd); return new JSONArray(jsonText); } finally { is.close(); } } 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(); }

Reference

No known

History May 08, 2017