简体   繁体   中英

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

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]));

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

Yes, the result of

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM