I'm creating a RESTFul Web Service with the following service available:
@RequestMapping(value = "/test", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<GenericModel>> returnEmpty() {
List<GenericModel> genericModelList = new ArrayList<>();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json; charset=utf-8");
return responseEntity = new ResponseEntity<>(genericModelList, headers, HttpStatus.OK);
}
When the empty list returns, I'm getting the following response in browser:
[]
How can I do to receive in browser a "null" response instead of []? There's some way to tell Spring to render my list size 0 as "null" and not as []?
ResponseEntity represents the whole HTTP response: status code, headers, and body. Because of it, we can use it to fully configure the HTTP response. If we want to use it, we have to return it from the endpoint; Spring takes care of the rest. ResponseEntity is a generic type. As a result, we can use any type as the response body: ?
Spring @ResponseBody @ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.
@ResponseStatus When an endpoint returns successfully, Spring provides an HTTP 200 (OK) response. If the endpoint throws an exception, Spring looks for an exception handler that tells which HTTP status to use. We can mark these methods with @ResponseStatus, and therefore, Spring returns with a custom HTTP status.
The application has two methods: one method uses ResponseEntity to create an HTTP response, the other one @ResponseBody . This is the project structure of the Spring application. This is the Maven pom.xml file. The spring-boot-starter-parent is a parent POM providing dependency and plugin management for applications built with Maven.
One way of pivoting it based on if the genericModelList
is empty of not could be:-
if(genericModelList.isEmpty()) {
return new ResponseEntity<>(null, headers, HttpStatus.OK);
} else {
return new ResponseEntity<>(genericModelList, headers, HttpStatus.OK);
}
or else you can skip the body
using ResponseEntity(MultiValueMap<String,String> headers, HttpStatus status)
constructor as well.
Because you just initialize the genericModelList
as an empty list, not null. Or you can check the size of list before sending response back with different body.
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