jayz
jayz

Reputation: 401

Get IMDB data to JSON array in java

I am doing a project using java. In that project I have to get the movie data from IMDB. So far I have learned that, using a direct link with movie id we can get the data as a JSON file.

http://www.omdbapi.com/?i=tt2975590&plot=full&r=json

I want to get this data to a JSON array in java. can someone help me with this. Thank you.

Upvotes: 0

Views: 1296

Answers (2)

thewmo
thewmo

Reputation: 775

There are fundamentally two tasks you need to solve for:

  • Making an HTTP request from your Java app to the URL endpoint
  • Converting the response data from serialized JSON to a data structure you can use in your application.

One approach would be to solve for these tasks separately. There is no shortage of good HTTP client libraries (Apache HttpComponents and Jetty HttpClient come to mind). And also no shortage of good libraries for manipulating JSON in Java. (Jackson, Google's GSON, others).

However, the "standard" way to interact with web services in Java is via the JAX-RS standard, of which Jersey is the reference implementation. The Jersey client module will allow you to perform the HTTP call and deserialize the JSON to a "bean-compliant" Java class in a single operation. See the Jersey documentation here:

https://jersey.java.net/documentation/latest/client.html

and here for information about JSON marshaling:

https://jersey.java.net/documentation/latest/media.html#json

All that said, if you only need to call one API and are just looking for the quickest way to get there, not necessarily the slickest solution, Apache HTTPComponents and Google GSON are probably the route I would take.

Good luck!

Upvotes: 1

Bertrand Martel
Bertrand Martel

Reputation: 45372

The download function that download the file & return the result :

private static String download(String urlStr) throws IOException {
    URL url = new URL(urlStr);
    String ret = "";
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    byte[] buffer = new byte[1024];
    int count = 0;
    while ((count = bis.read(buffer, 0, 1024)) != -1) {
        ret += new String(buffer, 0, count);
    }
    bis.close();
    return ret;
}

Build JsonObject & convert to JsonArray like that :

try {
    String ret = download("http://www.omdbapi.com/?i=tt2975590&plot=full&r=json");

    if (ret != null) {

        JSONObject items = new JSONObject(ret);
        Iterator x = items.keys();
        JSONArray jsonArray = new JSONArray();

        while (x.hasNext()) {
            String key = (String) x.next();
            jsonArray.put(items.get(key));
            System.out.println(key + " : " + items.get(key));
        }
    }

} catch (IOException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}

Upvotes: 1

Related Questions