将 IMDB 数据获取到 java 中的 JSON 数组

Get IMDB data to JSON array in java

我正在使用 java 做一个项目。在那个项目中,我必须从 IMDB 获取电影数据。到目前为止,我了解到,使用带有电影 ID 的直接 link,我们可以将数据作为 JSON 文件获取。

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

我想将此数据放入 java 中的 JSON 数组。有人可以帮我弄这个吗。谢谢。

下载文件的下载函数&return结果:

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;
}

构建 JsonObject 并转换为 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();
}

从根本上说,您需要解决两个任务:

  • 从您的 Java 应用向 URL 端点发出 HTTP 请求
  • 将响应数据从序列化 JSON 转换为可在应用程序中使用的数据结构。

一种方法是分别解决这些任务。不乏优秀的 HTTP 客户端库(想到 Apache HttpComponents 和 Jetty HttpClient)。而且也不乏用于在 Java 中操作 JSON 的优秀库。 (杰克逊,Google 的 GSON,其他人)。

但是,"standard" 在 Java 中与 Web 服务交互的方式是通过 JAX-RS 标准,Jersey 是该标准的参考实现。 Jersey 客户端模块将允许您在单个操作中执行 HTTP 调用并将 JSON 反序列化为 "bean-compliant" Java class。请在此处查看 Jersey 文档:

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

这里是关于 JSON 编组的信息:

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

综上所述,如果您只需要调用一个 API 并且只是在寻找到达那里的最快方式,不一定是最巧妙的解决方案,Apache HTTPComponents 和 Google GSON 可能是我要走的路线。

祝你好运!