1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStream;
4import java.io.InputStreamReader;
5import java.io.Reader;
6import java.net.URL;
7import java.nio.charset.Charset;
8
9import org.json.JSONException;
10import org.json.JSONObject;
11
12public class JsonReader {
13
14 private static String readAll(Reader rd) throws IOException {
15 StringBuilder sb = new StringBuilder();
16 int cp;
17 while ((cp = rd.read()) != -1) {
18 sb.append((char) cp);
19 }
20 return sb.toString();
21 }
22
23 public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
24 InputStream is = new URL(url).openStream();
25 try {
26 BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
27 String jsonText = readAll(rd);
28 JSONObject json = new JSONObject(jsonText);
29 return json;
30 } finally {
31 is.close();
32 }
33 }
34}
1//include org.json:json as a dependency
2try(BufferedReader br=new BufferedReader(new InputStreamReader(new URL("URL here").openStream()))){
3 JSONObject json=new JSONObject(br.lines().collect(Collectors.joining()));
4 json.getString("hello");//gets the String of the key named "hello"
5 json.getInt("world");//gets the integer value of the key named "world"
6 json.getJSONObject("test");//gets the JSONObject value representation of the key "test", you can use the getXXX methods on the returned object
7 json.getJSONObject("test").getString("something");
8}
9
10/* JSON data:
11{
12 "hello": "some string",
13 "world": 1234,
14 "test":{
15 "something": "else"
16 }
17}
18*/