我有一个api,当它是收视率最高的电影时,会返回等值
[
{
"movieId":"o1",
"movie name":"Dory",
"rating":"Best"
}
]
如果没有,则返回
[
{
"movieId":null,
"movie name":null,
"rating":null
}
]
我使用了一个rest模板,该模板使用执行方法调用api
public List<Movies> getRatingViaApi(String id){
RestTemplate restTemplate = new RestTemplate();
//String resourceUrl = "http://localhost:8080/movies";
RequestCallback requestCallback = request -> {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(request.getBody(),
id);
request.getHeaders()
.setAccept(Arrays.asList(
MediaType.APPLICATION_OCTET_STREAM,
MediaType.ALL));
};
ResponseExtractor<List<Movies>> responseExtractor = response ->
ObjectMapper mapper= new ObjectMapper ();
return mapper.readValue(response.getBody(),new TypeReference<List<Movies>>(){});
};
restTemplate.execute(resourceUrl,
HttpMethod.GET,
requestCallback,
responseExtractor );
}
如何检查Api响应是否给出空值或者它是否是最好的电影
你想要这样的东西吗?
@Data
public class Movies {
private static final String THE_BEST_RATING = "Best";
private String movieId;
private String movieName;
private String rating;
public boolean isPresent() {
return ObjectUtils.allNull(movieId, movieName, rating);
}
public boolean isTheBest() {
return Objects.equals(THE_BEST_RATING, rating);
}
}
使用示例:
public static void main(String[] args) {
// ...
// download list
List<Movies> existingMovies = moviesList.stream() // list of "non null objects"
.filter(Movies::isPresent)
.collect(toCollection(ArrayList::new));
existingMovies.stream()
.filter(Movies::isTheBest)
.forEach(movie -> System.out.println("Movie: " + movie + " is the best")); //printing the bests movies
}