Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can restTemplate.getForObject("URL", Object[].class) return NULL?

Tags:

I have used the solution from this answer: Get list of JSON objects with Spring RestTemplate It works perfectly. It doing exactly what I need.

ProcessDefinition[] response = restTemplate.getForObject(url, ProcessDefinition[].class);

Is it enought:

return Arrays.asList(response);

or will be better this way:

return Arrays.asList(Optional.ofNullable(response).orElse(new ProcessDefinition[0]));

P.S. Sorry for starting the new topic, but my karma does not allow me to comment the answer.

like image 634
virtuemaster Avatar asked Nov 15 '17 07:11

virtuemaster


People also ask

What is difference between getForObject and getForEntity in RestTemplate?

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.

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.

What does RestTemplate exchange return?

The exchange method executes the request of any HTTP method and returns ResponseEntity instance. The exchange method can be used for HTTP DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE methods. Using exchange method we can perform CRUD operation i.e. create, read, update and delete data.


1 Answers

Yes, the result of

ProcessDefinition[] response = restTemplate.getForObject(url, ProcessDefinition[].class);

can be null if HTTP response body was empty (not [], but totally empty body).

So it is safer to check it if you are not sure that HTTP response never be empty.

return Optional.ofNullable(response).map(Arrays::asList).orElseGet(ArrayList::new)

or

return Optional.ofNullable(response).map(Stream::of).orElseGet(Stream::empty)

if you need a stream.

like image 134
Ruslan Stelmachenko Avatar answered Sep 20 '22 12:09

Ruslan Stelmachenko