How to get List from Object in Spring RestTemplate

Tags: , , , ,



How to get List from Object? Below you can find my code:

ResponseEntity<Object> responseEntity = restTemplate.getForEntity("localhost:8083/connectors/", Object.class);
Object object = responseEntity.getBody();

Actually object variable is a List of Objects(Strings) and I need to get all these Strings.

If I print it out System.out.println(object.toString()); it looks like that:

[objvar, values, test, object, servar, larms, aggregates, sink, records]

I need to get List of these Strings to dynamic use it. Could you please help?

Answer

Try this out. This should work.

ResponseEntity<String[]> responseEntity = restTemplate.getForEntity("localhost:8083/connectors/", String[].class);
List<String> object = Arrays.asList(responseEntity.getBody());

For simple cases the code above works, but when you have complex json structures which you want to map, then it is ideal to use ParameterizedTypeReference.

ResponseEntity<List<String>> responseEntity =
        restTemplate.exchange("localhost:8083/connectors/",
            HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
            });
List<String> listOfString = responseEntity.getBody();


Source: stackoverflow