Capture the values of JSON that is Online

Asked

Viewed 3,497 times

23

My problem:

I need to read a JSON that is in a certain 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)

Remarks:

  • This code is an example and does not include the try{}catch(...){} in the example, someone has some notion of how to solve this problem or why it is occurring?
  • I tried to use String x = url.toString() but I also got the same error.
  • Good question formatting, all well organized :)

  • Look, I know very little about Java, but you shouldn’t pass a string to the parser instead of a Streamreader?

  • Well the Jsonparser class has two parse(String s) and parse(Reader in) methods. As I was reading a local JSON I used Reader, but now the need is another.

4 answers

11

When you call the method toString() in a InputStream, it will not return the contents of the stream, but rather its memory address. Read a little more about the method toString() here.

You should take the http connection stream and use it to build a Reader and then use the 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);

7


You already have the stream that is returned by openStream(). Just pass as argument from InputStreamReader:

Reader reader = new InputStreamReader( url.openStream() );
  • Thank you, problem solved. My error was trying to use "getClass(). getResourceAsStream(x)" and should not since it is a remote file. Thank you @helderdarocha.

6

What you can use to not have to do everything in hand is the:

com.google.common.io.Resources.

So, to recover the data from the URL, just do:

URL url = new URL( urlString );
return Resources.toString( url, Charsets.UTF_8 );

Another tip is to use:

com.google.gson.Gson.Gson()

To retrieve the object directly from JSON, thus:

new Gson().fromJson( objetoEmString, ClasseDestinoDaConversao.class );

So, with little code, everything is ready.

Documentations (in English):

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Resources.html

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

3

Good morning.

Just trying to complement the previous answers, when parsing the Object -> JSON/JSON -> Object, I prefer to use the Jackson. It supports JAXB specification. What’s good for you to write less framework-coupled code.

Anyway. There is an example of the mkyong (which by the way is a site that I really like picking up examples) that I think can help you. The only difference is that it reads the JSON of a file, but the principle is the same.

You changing the line that reads the file by readTree(json) (where json is the JSON string itself) already replaces.

The code is as follows:.

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) {

    ObjectMapper mapper = new ObjectMapper();

    try {

        // read from file, convert it to user class
        User user = mapper.readValue(new File("c:\\user.json"), User.class);

        // display to console
        System.out.println(user);

    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

  }

}

I hope I helped a little.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.