Return null in ResponseEntity body (Spring Boot RESTful)

Viewed 25962

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 []?

3 Answers

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.

Thanks everybody, I will try to be more clear next time. I solved the problem.

I was trying to send "null" in the body of my ResponseEntity> when my List size is 0, but Jackson creates a "[]" JSON and not a "null" as I wanted. I didn't found a way to change this default Jackson's bahavior, so I decided to abandon Jackson and use the Gson library.

Let me show a example of my solution:

@RequestMapping(value = "/test", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<String> returnEmpty() {

    List<GenericModel> genericModelList = new ArrayList<>();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=utf-8");

    String body = "";

    if (genericModelList.size() == 0) {
        body = "null";
    } else {
        body = gson.toJson(genericModelList);
    }

    return responseEntity = new ResponseEntity<>(body, headers, HttpStatus.OK);
}

This way, returning a String and parsing to JSON myself with Gson instead of use automatic parsing from Spring/Jackson, I can control the resulting JSON. Look that I explicity return a String "null" if my List.size() == 0.

Related