从 REST API 过滤 JSON 对象的疑问
Posted
技术标签:
【中文标题】从 REST API 过滤 JSON 对象的疑问【英文标题】:Doubts to filter JSON objects from REST API 【发布时间】:2019-04-30 03:48:30 【问题描述】:我正在尝试从 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 ObjectMapper 将 json 字符串读取到 MapObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode= mapper.readValue("yourJsonOutputAsString", JsonNode.class); String genre=(String) json.get("Genre");
您应该将其插入到单独的方法中,因为最好将每个方法分配给仅执行单个任务。
【参考方案1】:
您可以使用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
格森:
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
额外帮助:
额外帮助:如果有人能告诉我如何在单独的行中打印输出,那将会很有帮助。
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);
【讨论】:
以上是关于从 REST API 过滤 JSON 对象的疑问的主要内容,如果未能解决你的问题,请参考以下文章
更改 URL 对 JSON 返回的 Django Rest 框架没有影响
如何在 Spring Boot REST API 中启用对 JSON / Jackson @RequestBody 的严格验证?