Spring Boot: Return a empty JSON instead of empty body when returned object is null
First, if you're using @RestController
annotation you don't need the @ResponseBody
annotation, get rid of that.
Second if you're trying to have REST Controller, then you're missing a few things, do it like this:
@RequestMapping(value = "/sigla/{sigla}", method = RequestMethod.GET, consumes = "application/json", produces="application/json")
public ResponseEntity<PaisDTO> obterPorSigla(@PathVariable String sigla) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
PaisDTO paisDTO = service.obterPorSigla(sigla);
if(paisDTO != null) return new ResponseEntity<>(paisDTO, headers, HttpStatus.OK);
else return new ResponseEntity<>(headers, HttpStatus.OK);
}
In the example above if you'll get null then you'll return an empty response JSON.
The only way that I could find was to create an empty class
@JsonSerialize
public class EmptyJsonBody {
}
Then add this to your response
@PostMapping(value = "/sigla/{sigla}")
public ResponseEntity obterPorSigla(@PathVariable String sigla) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
PaisDTO paisDTO = service.obterPorSigla(sigla);
ResponseEntity.BodyBuilder responseBuilder = ResponseEntity.ok().headers(headers);
if(paisDTO != null) {
return responseBuilder.body(paisDTO);
} else {
return responseBuilder.body(new EmptyJsonBody());
}
}
Solution 1: You have to implement you entity class with Serializable Solution 2: Your class should have getter and setter In my case the getter and setter were given protected access modifiers. so I changed them to public and vola it worked