我有一个 RestController ,当我调用该方法时:
@RequestMapping(value = "/sigla/{sigla}")
@ResponseBody
public PaisDTO obterPorSigla(@PathVariable String sigla) {
return service.obterPorSigla(sigla);
}
如果找到一条记录,我会得到一个很好的 JSON 响应:
{"nome":"Brasil","sigla":"BR","quantidadeEstados":27}
但是当在数据库上没有找到任何东西时, RestController 返回 null 并且我得到一个空的响应,完全空白的主体。
如何显示空 JSON 而不是空白响应?像下面这样:
{}
完整的 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);
}
请您参考如下方法:
首先,如果您使用的是 @RestController
您不需要的注释 @ResponseBody
注释,摆脱它。
其次,如果您尝试使用 REST Controller,那么您会遗漏一些东西,请这样做:
@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);
}
在上面的示例中,如果您将获得 null,那么您将返回一个空的响应 JSON。