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?
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With