214

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

cassiomolin
  • 101,346
  • 24
  • 214
  • 283
Karudi
  • 2,372
  • 3
  • 15
  • 19
  • 2
    Consider see this answer, specially if you want use generics list https://stackoverflow.com/questions/36915823/spring-resttemplate-and-generic-types-parameterizedtypereference-collections-lik/53398952#53398952 – Moesio Nov 20 '18 at 18:15

11 Answers11

358

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[].

Matt
  • 3,915
  • 1
  • 15
  • 6
  • 6
    This run's smoothly with Spring 4.2.3 and - as Matt said - has the big advantage of avoiding the Object[] – Marged Dec 16 '15 at 12:21
  • @Matt - which marshaller are you using to marshal the json into Rate objects? I am guessing that's what's happening here, at the time of the `restTemplate.exchange` a marshallar maps all the json values to the matching key names as properties in the Rate object. Hope my thought process is correct. – Nirmal Mar 28 '16 at 20:14
  • Perfect, works fine in Spring Boot 1.4.0.RELEASE Thanks – Anand Sep 29 '16 at 04:59
  • 1
    @Nirmal Spring uses Jackson by default I believe. – Sohaib Mar 31 '17 at 13:28
  • Thanks for ParameterizedTypeReference – Rohit Jul 12 '17 at 05:08
  • ParameterizedTypeReference is @deprecated – Sarvar Nishonboyev May 25 '19 at 11:55
  • 1
    @SarvarNishonboev the current ParameterizedTypeReference from springframework.core still seems fine: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/ParameterizedTypeReference.html – fspinnenhirn Oct 26 '19 at 00:24
241

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().

Matthias Wiehl
  • 1,288
  • 10
  • 18
kamokaze
  • 6,497
  • 4
  • 31
  • 39
  • That worked like a charm , thank you . Maybe you can direct me to some other tutorials or guides that I could read on this topic ? – Karudi May 15 '14 at 11:18
  • 2
    best to look here on stackoverflow for some code snippets and examples or visit the offial spring website...... TblGps[] a = responseEntity.getBody(); – kamokaze May 15 '14 at 11:29
  • Is it possible to this using generics? i.e. my method has a Class parameter and I would like to get a collection of T from the getForEntity method. – Diskutant Mar 20 '15 at 12:52
  • Yes it should work, but might not be out of the box depending on your spring/jackson version and your class types. Its all about serializing/deserializing generics - the http Request istself does not care what is transported. – kamokaze Mar 21 '15 at 10:42
  • 1
    Also see http://forum.spring.io/forum/spring-projects/android/125835-how-to-get-a-list-myobject-via-resttemplate. – Benny Bottema Mar 11 '16 at 14:29
  • @kamokaze, can you please take a look related question stackoverflow.com/q/48230251/2674303 ? – gstackoverflow Jan 13 '18 at 08:16
77

For me this worked

Object[] forNow = template.getForObject("URL", Object[].class);
    searchList= Arrays.asList(forNow);

Where Object is the class you want

yonia
  • 1,591
  • 1
  • 12
  • 11
  • 17
    This works even if you use a class and not Object like ```Coupon[] coupons = restTemplate.getForObject( url, Coupon[].class)``` – lrkwz Dec 02 '15 at 16:06
  • 1
    This can cause NPE if HTTP response body was empty (not `[]` but totally empty). So be careful and check for `null` (`if (forNow != null)...`). – Ruslan Stelmachenko Dec 10 '17 at 03:55
  • 1
    Saved my ass :) Wondering what type is used by Jackson, when `Object.class` is specified in method `getForObject()`. – user218867 May 28 '19 at 07:09
8

You can create POJO for each entry like,

class BitPay{
private String code;
private String name;
private double rate;
}

then using ParameterizedTypeReference of List of BitPay you can use as:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
  "https://bitpay.com/api/rates",
  HttpMethod.GET,
  null,
  new ParameterizedTypeReference<List<BitPay>>(){});
List<Employee> employees = response.getBody();
Nitin Pawar
  • 1,358
  • 16
  • 13
5

After multiple tests, this is the best way I found :)

Set<User> test = httpService.get(url).toResponseSet(User[].class);

All you need there

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}
Romain-p
  • 583
  • 1
  • 4
  • 21
5

If you would prefer a List of POJOs, one way to do it is like this:

class SomeObject {
    private int id;
    private String name;
}

public <T> List<T> getApi(final String path, final HttpMethod method) {     
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<List<T>> response = restTemplate.exchange(
      path,
      method,
      null,
      new ParameterizedTypeReference<List<T>>(){});
    List<T> list = response.getBody();
    return list;
}

And use it like so:

 List<SomeObject> list = someService.getApi("http://localhost:8080/some/api",HttpMethod.GET);

Explanation for the above can be found here (https://www.baeldung.com/spring-rest-template-list) and is paraphrased below.

"There are a couple of things happening in the code above. First, we use ResponseEntity as our return type, using it to wrap the list of objects we really want. Second, we are calling RestTemplate.exchange() instead of getForObject().

This is the most generic way to use RestTemplate. It requires us to specify the HTTP method, optional request body, and a response type. In this case, we use an anonymous subclass of ParameterizedTypeReference for the response type.

This last part is what allows us to convert the JSON response into a list of objects that are the appropriate type. When we create an anonymous subclass of ParameterizedTypeReference, it uses reflection to capture information about the class type we want to convert our response to.

It holds on to this information using Java’s Type object, and we no longer have to worry about type erasure."

Toofy
  • 596
  • 6
  • 14
3

My big issue here was to build the Object structure required to match RestTemplate to a compatible Class. Luckily I found http://www.jsonschema2pojo.org/ (get the JSON response in a browser and use it as input) and I can't recommend this enough!

upnorth
  • 51
  • 3
2

i actually deveopped something functional for one of my projects before and here is the code :

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the return type you are expecting. Exemple : someClass.class
 */

public static <T> T getObject(String url, Object parameterObject, Class<T> returnType) {
    try {
        ResponseEntity<T> res;
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        String json = mapper.writeValueAsString(restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, returnType).getBody());
        return new Gson().fromJson(json, returnType);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the type of the returned object. Must be an array. Exemple : someClass[].class
 */
public static <T> List<T> getListOfObjects(String url, Object parameterObject, Class<T[]> returnType) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        ResponseEntity<Object[]> results = restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, Object[].class);
        String json = mapper.writeValueAsString(results.getBody());
        T[] arr = new Gson().fromJson(json, returnType);
        return Arrays.asList(arr);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

I hope that this will help somebody !

1

Consider see this answer, specially if you want use generics in List Spring RestTemplate and generic types ParameterizedTypeReference collections like List<T>

Moesio
  • 2,782
  • 1
  • 24
  • 36
1

In my case I preferred to extract a String then browse the context using JsonNode interface

    var response =  restTemplate.exchange("https://my-url", HttpMethod.GET, entity,  String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        var jsonString = response.getBody();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonString);           
        
        System.out.println(actualObj);  
    }

or quickly

ObjectNode actualObj= restTemplate.getForObject("https://my-url", ObjectNode.class);

then read inner data with path expression i.e.

boolean b = actualObj.at("/0/states/0/no_data").asBoolean();
Roberto Petrilli
  • 168
  • 1
  • 1
  • 12
-1

I found work around from this post https://jira.spring.io/browse/SPR-8263.

Based on this post you can return a typed list like this:

ResponseEntity<? extends ArrayList<User>> responseEntity = restTemplate.getForEntity(restEndPointUrl, (Class<? extends ArrayList<User>>)ArrayList.class, userId);
naXa
  • 26,677
  • 15
  • 154
  • 213
Shravan Ramamurthy
  • 3,044
  • 2
  • 21
  • 38
  • 4
    This won't work, because due to erasure no type parameter information is passed to `getForEntity`. Also `(Class extends ArrayList>) ArrayList.class` gives an "incompatible types" compile error. – Esko Luontola Oct 05 '15 at 15:15