Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get List from Object in Spring RestTemplate

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?

like image 975
Tom Avatar asked Apr 10 '18 11:04

Tom


People also ask

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.

Does RestTemplate use Okhttp?

Okhttp3 is a quite popular http client implementation for Java and we can easily embed it into Spring RestTemplate abstraction. Following bean declaration will make the default RestTemplete binding instance an Okhttp3 client. You can just autowire the Resttemplate to use this customized Okhttp3 based resttemplate.

What is RestTemplate getForObject?

The getForObject method fetches the data for the given response type from the given URI or URL template using HTTP GET method. To fetch data for the given key properties from URL template we can pass Object Varargs and Map to getForObject method. The getForObject returns directly the object of given response type.


1 Answers

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();
like image 54
pvpkiran Avatar answered Oct 01 '22 07:10

pvpkiran