Return null to body ResponseEntity (Spring Boot RESTful)

I am creating a RESTFul web service with the following service:

@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 an empty list returns, I get the following response in the browser:

[]

How can I do to get a “null” response in the browser instead of []? Is there some way I could tell Spring to have my list size 0 be "null" and not like []?

+4
source share
3 answers

One of the ways to rotate it, based on what is genericModelListempty, cannot be: -

if(genericModelList.isEmpty()) {
    return new ResponseEntity<>(null, headers, HttpStatus.OK);
} else {
    return new ResponseEntity<>(genericModelList, headers, HttpStatus.OK);
}

otherwise you can skip bodyusing ResponseEntity(MultiValueMap<String,String> headers, HttpStatus status).

+2
source

genericModelList , null. .

+1

, . .

"null" ResponseEntity > , 0, "[]" JSON, "", . - , Gson.

:

@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);
}

, String JSON Gson Spring/Jackson, JSON. , String "null", List.size() == 0.

0

Source: https://habr.com/ru/post/1686783/


All Articles