简体   繁体   English

从 REST API 过滤 JSON 对象的疑惑

[英]Doubts to filter JSON objects from REST API

I am trying to filter some objects from a JSON response in Java.我正在尝试从 Java 的 JSON 响应中过滤一些对象。 Below is my code.下面是我的代码。 I need to get the Genre Object from the response and print it separately.我需要从响应中获取流派对象并单独打印。 Anyone who knows how that can be done?任何人都知道如何做到这一点?

I have did the RestAPI call from omdb.我已经从 omdb 调用了 RestAPI。 This is a just a simple project which I am trying to build.这只是一个我正在尝试构建的简单项目。 To basically analyze the type of genres that were released in particular years.基本分析特定年份发行的类型。


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));*/

    }
}

Output:输出:

{"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"}

This is the output, can I know how do I filter out just the Genre in this output.这是输出,我可以知道如何仅过滤掉此输出中的流派。

Extra help : If someone could tell me how to print the output in separate lines, it will be helpful.额外的帮助:如果有人能告诉我如何在单独的行中打印输出,那将会很有帮助。

You can parse it using the jackson library.您可以使用jackson库解析它。 Can you try this code?你能试试这个代码吗?

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:额外帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM