【问题标题】:Get IMDB data to JSON array in java在java中获取IMDB数据到JSON数组
【发布时间】:2016-11-19 07:40:15
【问题描述】:

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

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

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

【问题讨论】:

标签: java imdb geojson


【解决方案1】:

下载文件并返回结果的下载函数:

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

【讨论】:

    【解决方案2】:

    基本上有两个任务需要解决:

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

    一种方法是分别解决这些任务。不乏优秀的 HTTP 客户端库(想到 Apache HttpComponents 和 Jetty HttpClient)。并且不乏用于在 Java 中操作 JSON 的优秀库。 (Jackson、Google 的 GSON 等)。

    但是,在 Java 中与 Web 服务交互的“标准”方式是通过 JAX-RS 标准,其中 Jersey 是参考实现。 Jersey 客户端模块将允许您在单个操作中执行 HTTP 调用并将 JSON 反序列化为“符合 bean 的”Java 类。请参阅此处的泽西岛文档:

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

    这里是关于 JSON 封送处理的信息:

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

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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多