java – Capture JSON values ​​that are Online


My problem:

I need to read a JSON that is at a given URL. I tried the following code, but it doesn't work:

JSONObject jsonObjeto;
JSONParser parser = new JSONParser();

URL url = new URL("");

String x = url.openStream().toString();
Reader reader = new InputStreamReader(getClass().getResourceAsStream(x));

jsonObjeto = (JSONObject) parser.parse(reader);

I get the following error:

Exception in thread "main" java.lang.NullPointerException


  • This code is an example and does not include the try{}catch(...){} in the example, does anyone have any idea how to solve this problem or why it is occurring?
  • I tried using String x = url.toString() but I also got the same error.


When you call the toString() method on an InputStream , it will not return the stream's contents, but its memory address. Read a little more about the toString() method here .

You should take the http connection stream and use it to build a Reader and then use JSONParser to parse the JSON.

URL url = new URL("");
Reader br = new InputStreamReader(url.openStream());

JSONParser parser = new JSONParser();
JSONObject jsonObjeto = (JSONObject) parser.parse(br);

Scroll to Top