java get json from url code example

Example: 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