2

我想从 OMDB API 获取电影数据,它是 JSON 文本。我正在使用 Java 来解码这个和 JSON-simple 包。

我要解码的 URL 是这样的,例如:http ://www.omdbapi.com/?t=icarus

结果(直接复制粘贴,非结构化):

{"Title":"Icarus","Year":"2010","Rated":"TV-14","Released":"10 Dec 2010","Runtime":"42 min","Genre": “冒险,戏剧,浪漫”,“导演”:“Mairzee Almas”,“作家”:“Alfred Gough(创作者),Jerry Siegel(角色创作者:超人),Miles Millar(创作者),Joe Shuster(角色创作者:超人)、阿尔弗雷德·高夫(为电视开发)、迈尔斯·米勒(为电视开发)、吉纳维芙·斯帕林、“演员”:“汤姆·威灵、埃里卡·杜兰斯、卡西迪·弗里曼、贾斯汀·哈特利”、“剧情”:“作为VRA 威胁加剧,克拉克采取主动关闭了望塔并宣布联盟正式转入地下,但这是否足以阻止 trotter 和 Slade Wilson...","Language":"English","Country":"USA","Awards":"N/A","Poster":"http://ia.media-imdb.com/images/M/MV5BMjIwNDQ2MjM5OV5BMl5BanBnXkFtZTcwODU4NzU0NA@@._V1_SX300.jpg ","Metascore":"N/A","imdbRating":"8.6","imdbVotes":"367" ,"imdbID":"tt1628582","Type":"episode","Response":"True"}

我的按钮下的代码:

        String url = "http://www.omdbapi.com/?t=" + jListFilms.getSelectedValue().toString();

    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(url);
        JSONObject jsonObj = (JSONObject) obj;

        String title = (String) jsonObj.get("Title") ;
        System.out.println(title);

    } catch (ParseException e){
        System.out.println(e);
    }

当我打印出变量标题时

位置 0 处的意外字符 (h)。

有人知道为什么我没有得到电影的名字吗?

4

2 回答 2

1

感谢亚当带领我走向正确的方向。我现在使用 InputStream 和 Google Gson 而不是 JSON.Simple。

这是我现在的代码,它可以按照我想要的方式工作。

        try {

        String selectedItem = jListFilms.getSelectedValue().toString().replace("\\s+", "+");

        InputStream input = new URL("http://www.omdbapi.com/?t=" + URLEncoder.encode(selectedItem, "UTF-8")).openStream();
        Map<String, String> map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), new TypeToken<Map<String, String>>(){}.getType());

        String title = map.get("Title");
        String year = map.get("Year");
        String released = map.get("Released");
        String runtime = map.get("Runtime");
        String genre = map.get("Genre");
        String actors = map.get("Actors");
        String plot = map.get("Plot");
        String imdbRating = map.get("imdbRating");
        String poster = map.get("Poster");

        testForm tf = new testForm(title, year, released, runtime, genre, actors, plot, imdbRating);
        tf.setVisible(true);

    } catch (JsonIOException | JsonSyntaxException | IOException e){
        System.out.println(e);
    }
于 2014-05-30T20:56:01.313 回答
1

您的代码正在做的是解析以“http://”开头的字符串 URL,因此是位置 0 处的 h。

您需要在该 url 发出 HTTP GET 请求才能取回 JSON。

这是关于如何发出 GET 请求的答案

于 2014-05-30T18:35:35.747 回答