Mapping RestTemplate response to java Object

user9735824 picture user9735824 · Feb 28, 2019 · Viewed 10.4k times · Source

I am using RestTemplate get data from remote rest service and my code is like this.

ResponseEntity<List<MyObject >> responseEntity = restTemplate.exchange(request, responseType);

But rest service will return just text message saying no record found if there are no results and my above line of code will throw exception. I could map result first to string and later use Jackson 2 ObjectMapper to map to MyObject.

ResponseEntity<String> responseEntity = restTemplate.exchange(request, responseType);
String jsonInput= response.getBody();
List<MyObject> myObjects = objectMapper.readValue(jsonInput, new TypeReference<List<MyObject>>(){});

But I don't like this approach. Is there any better solution for this.

Answer

Carlos picture Carlos · Mar 14, 2019

What I usually do in my projects with restTemplate is save the response in a java.util.Map and create a method that converts that Map in the object I want. Maybe saving the response in an abstract object like Map helps you with that exception problem.

For example, I make the request like this:

List<Map> list = null;
List<MyObject> listObjects = new ArrayList<MyObject>();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);

if (response != null && response.getStatusCode().value() == 200) {
    list = (List<Map>) response.getBody().get("items"); // this depends on the response
    for (Map item : list) { // we iterate for each one of the items of the list transforming it
        MyObject myObject = transform(item);
        listObjects.add(myObject);
    }
}

The function transform() is a custom method made by me: MyObject transform(Map item); that receives a Map object and returns the object I want. You can check if there was no records found first instead of calling the method transform.