Java – Get list of JSON objects with Spring RestTemplate

javaresttemplatespring

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/.

Best Answer

First define an object to hold the entity coming back in the array.. e.g.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Rate {
    private String name;
    private String code;
    private Double rate;
    // add getters and setters
}

Then you can consume the service and get a strongly typed list via:

ResponseEntity<List<Rate>> rateResponse =
        restTemplate.exchange("https://bitpay.com/api/rates",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<Rate>>() {
            });
List<Rate> rates = rateResponse.getBody();

The other solutions above will also work, but I like getting a strongly typed list back instead of an Object[].