Search code examples
javaspringresttemplate

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

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


Solution

  • 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.