Question:
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("http://www.exemplo.br/teste.json");
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
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
Comments:
- 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.
Answer:
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("http://www.exemplo.br/teste.json");
Reader br = new InputStreamReader(url.openStream());
JSONParser parser = new JSONParser();
JSONObject jsonObjeto = (JSONObject) parser.parse(br);
System.out.println(jsonObjeto);