get json response from url in java code example

Example 1: how to read a .json from web api java

try {
			URL url = new URL("url");
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();
			if(conn.getResponseCode() == 200) {
				Scanner scan = new Scanner(url.openStream());
				while(scan.hasNext()) {
					String temp = scan.nextLine();
                  	//parse json here
                }
            }
}

Example 2: java get json from url

//include org.json:json as a dependency
try(BufferedReader br=new BufferedReader(new InputStreamReader(new URL("URL here").openStream()))){
	JSONObject json=new JSONObject(br.lines().collect(Collectors.joining()));
    json.getString("hello");//gets the String of the key named "hello"
    json.getInt("world");//gets the integer value of the key named "world"
    json.getJSONObject("test");//gets the JSONObject value representation of the key "test", you can use the getXXX methods on the returned object
    json.getJSONObject("test").getString("something");
}

/* JSON data:
{
	"hello": "some string",
    "world": 1234,
    "test":{
    	"something": "else"
    }
}
*/

Tags:

Java Example