Search code examples
javaspringresttemplate

Get list of JSON objects with Spring RestTemplate


I have two questions:

  • How to map a list of JSON objects using Spring RestTemplate.
  • How to map nested JSON objects.

I am trying to consume https://bitpay.com/api/rates, by following the tutorial from http://spring.io/guides/gs/consuming-rest/.


Solution

  • Maybe this way...

    ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity(urlGETList, Object[].class);
    Object[] objects = responseEntity.getBody();
    MediaType contentType = responseEntity.getHeaders().getContentType();
    HttpStatus statusCode = responseEntity.getStatusCode();
    

    Controller code for the RequestMapping

    @RequestMapping(value="/Object/getList/", method=RequestMethod.GET)
    public @ResponseBody List<Object> findAllObjects() {
    
        List<Object> objects = new ArrayList<Object>();
        return objects;
    }
    

    ResponseEntity is an extension of HttpEntity that adds a HttpStatus status code. Used in RestTemplate as well @Controller methods. In RestTemplate this class is returned by getForEntity() and exchange().