Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3744

Spring Boot: Return a empty JSON instead of empty body when returned object is null

$
0
0

I have a RestController and when I call the method:

@RequestMapping(value = "/sigla/{sigla}")@ResponseBodypublic PaisDTO obterPorSigla(@PathVariable String sigla) {    return service.obterPorSigla(sigla);}

If a record is found, I get a good JSON response:

{"nome":"Brasil","sigla":"BR","quantidadeEstados":27}

but when nothing is found on database the RestController returns null and I get a empty response, completely blank body.

How can I display a empty JSON instead of a blank response? Like bellow:

{}

Complete Controller:

@RestController@RequestMapping("/pais")public class PaisController {    @Autowired    private PaisService service;    @RequestMapping    public ResponseEntity<List<PaisDTO>> obterTodos() {        return CreateResponseEntity.getResponseEntity(service.obterTodos());    }    @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>(paisDTO, headers, HttpStatus.OK);        else return new ResponseEntity<PaisDTO>(headers, HttpStatus.OK);    }

Viewing all articles
Browse latest Browse all 3744

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>