0

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

1
  • you need to create a pojo matching your json. Commented Mar 6, 2018 at 9:45

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's solved my problem! Maybe you know any pattern which I should use in my app which I described in main post? My main problem is to transfer this data which I fetched (thanks to you) to Rest controller.
I think you should use object mapper to transfer that data directly to bean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.