gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:28:16 27 4
gpt4 key购买 nike

我有一个 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。

关于json - Spring Boot : Return a empty JSON instead of empty body when returned object is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837846/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com