java - 对从 REST API 中过滤 JSON 对象的疑问

标签 java json bigdata analytics

我正在尝试从 Java 中的 JSON 响应中过滤一些对象。下面是我的代码。我需要从响应中获取流派对象并单独打印它。谁知道如何做到这一点?

我已经从 omdb 进行了 RestAPI 调用。这只是我正在尝试构建的一个简单项目。基本上分析特定年份发行的类型。


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import sun.org.mozilla.javascript.internal.json.JsonParser;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class OmdbApiService {

    //public static final String Search_Url = "http://www.omdbapi.com/?s=TITLE&apikey=APIKEY";
    //public static final String Search_Url = "http://www.omdbapi.com/?t=TITLE&plot=PLOT&apikey=APIKEY";
    public static final String Search_Plot = "http://www.omdbapi.com/?i=TITLE&plot=PLOT&apikey=APIKEY";

    private static String sendGetRequest(String requestURL){
        StringBuffer response = new StringBuffer();

        try {
            URL url = new URL(requestURL);
            HttpURLConnection connection =
                    (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            InputStream stream = connection.getInputStream();
            InputStreamReader reader = new InputStreamReader(stream);
            BufferedReader buffer = new BufferedReader(reader);
            String line;
            while ((line = buffer.readLine()) != null) {
                response.append(line);
            }
            buffer.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response.toString();
    }

    private static String searchMoviebyID(String title, String plot, String key) {
        try {
            title = URLEncoder.encode(title, "UTF-8"); // To omit the spaces in between the titles
            plot = URLEncoder.encode(plot, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String requestUrl = Search_Plot
                .replaceAll("TITLE", title)
                .replaceAll("PLOT", plot)
                .replaceAll("APIKEY", key);
        return sendGetRequest(requestUrl);
    }

    /*private static String filterbyGenres(){
        try {



        }

    }*/


    public static void main(String[] args) {
        String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836","full","6d****87");
        System.out.println(jsonResponse);

        /*Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonElement jsonElement =  new JsonParser().parse(jsonResponse);
        System.out.println(gson.toJson(jsonResponse));*/

    }
}

输出:

{"Title":"The Dark Knight Rises","Year":"2012","Rated":"PG-13","Released":"20 Jul 2012","Runtime":"164 min","Genre":"Action, Thriller","Director":"Christopher Nolan","Writer":"Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)","Actors":"Christian Bale, Gary Oldman, Tom Hardy, Joseph Gordon-Levitt","Plot":"Despite his tarnished reputation after the events of The Dark Knight, in which he took the rap for Dent's crimes, Batman feels compelled to intervene to assist the city and its police force which is struggling to cope with Bane's plans to destroy the city.","Language":"English, Arabic","Country":"UK, USA","Awards":"Nominated for 1 BAFTA Film Award. Another 38 wins & 102 nominations.","Poster":"https://m.media-amazon.com/images/M/MV5BMTk4ODQzNDY3Ml5BMl5BanBnXkFtZTcwODA0NTM4Nw@@._V1_SX300.jpg","Ratings":[{"Source":"Internet Movie Database","Value":"8.4/10"},{"Source":"Rotten Tomatoes","Value":"87%"},{"Source":"Metacritic","Value":"78/100"}],"Metascore":"78","imdbRating":"8.4","imdbVotes":"1,372,667","imdbID":"tt1345836","Type":"movie","DVD":"03 Dec 2012","BoxOffice":"$448,130,642","Production":"Warner Bros. Pictures","Website":"http://www.thedarkknightrises.com/","Response":"True"}

这是输出,我能否知道如何仅过滤掉此输出中的流派。

额外帮助:如果有人可以告诉我如何在单独的行中打印输出,那将会很有帮助。

最佳答案

您可以使用jackson库来解析它。你能试试这个代码吗?

jackson :

// jackson library import
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

// ...
private static String filterByGenres(String jsonResponse) {
    String genres = "";
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readValue(jsonResponse, JsonNode.class);

        // Considering when there are no API results
        if(jsonNode != null || jsonNode.get("Genre") != null) {
            genres = jsonNode.get("Genre").asText();
        }
    } catch (Exception e) {
        // handle to exception
    }
    return genres;
}

public static void main(String[] args) {
    String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");

    // The result of the API is the argument.(json format string)
    String genres = filterByGenres(jsonResponse);
    System.out.println(genres); // Action, Thriller
}


Gson:

public static void main(String[] args) {
    String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");

    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = jsonParser.parse(jsonResponse).getAsJsonObject();
    JsonElement genreObject = jsonObject.get("Genre");
    System.out.println(genreObject.getAsString()); // Action, Thriller
}


额外帮助:

Extra help : If someone could tell me how to print the output in separate lines, it will be helpful.

public void prettyPrint() {
    String jsonResponse = OmdbApiService.searchMoviebyID("tt1345836", "full", "6d****87");

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonElement jsonElement = new JsonParser().parse(jsonResponse);
    String prettyJson = gson.toJson(jsonElement);
    System.out.println(prettyJson);
}

关于java - 对从 REST API 中过滤 JSON 对象的疑问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913704/

相关文章:

java - 正则表达式 URL 检查

ios - Json 和变量范围

javascript - 如何使用 AngularJs 从两个不同的 json 文件创建嵌套列表?

hive - Hive 表名最大字符数限制是多少?

node.js - 如何抓取网络以查找围绕某个主题的链接/网站?

java - 编译器无法识别我的 .getPoint 输入

Java:实现 "repeat until no change"集合

java - 使用 TRANSFORM 和 PIVOT 的交叉表查询重复行

java - 如何在Java数据模型类中拥有动态数据类型变量?

hadoop - 如何解决Hive中过多的分区问题