Reputation: 79
I've just started new project.
My backend client is fetching json from external API, wrap it to right model and then frontend can fetch this transformed data.
My problem is that I am receivig this format of json:
{
"page": 1,
"total_results": 52,
"total_pages": 3,
"results": [
{
{Movie1 data}
{Movie2 data}
{Movie3 data}
...
}
]
}
I would like to fetch only Movies data, so I created Movie model, but it cannot deserialize it.
Here is my code:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
String resourceURL = url;
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Movie[]> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity, Movie[].class);
if (response.getStatusCode() == HttpStatus.OK) {
for (Movie movie : response.getBody()) {
System.out.println(movie.originalTitle);
}
}
else
{
System.out.println("Error");
}
How I could fetch data from results array? Greetnigs Bartek
Upvotes: 0
Views: 89
Reputation: 27048
You need to create a pojo matching your json. Currently, you are trying to match your json to Movie[], which is not correct.
Try this
@JsonIgnoreProperties(ignoreUnknown = true)
class MovieResult {
List<Movie> results;
//Getters and Setters
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Movie {
//Getters and Setters
}
ResponseEntity<MovieResult> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity, MovieResult.class);
MovieResult movieResult = response.getBody();
List<Movie> movies = movieresult.getResults();
Upvotes: 1