我有一个 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 而不是空白响应?就像下面这样:
{}
完整控制器:
@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);
}
解决方案1: 您必须使用 Serialized 实现实体类 解决方案2: 你的类应该有 getter 和 setter 在我的例子中,getter 和 setter 被赋予了受保护的访问修饰符。所以我把它们改为公开,vola 成功了
首先,如果您使用
@RestController
注释,则不需要 @ResponseBody
注释,请将其删除。
其次,如果您尝试使用 REST 控制器,那么您会错过一些东西,请这样做:
@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。
我能找到的唯一方法是创建一个空类
@JsonSerialize
public class EmptyJsonBody {
}
然后将此添加到您的回复中
@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());
}
}
您可以使用
PaisDTO
注释来注释 @JsonInclude(Include.NON_NULL)
类
@JsonInclude(Include.NON_NULL)
public record PaisDTO{
...
}
然后,当您没有得到任何结果时,您只需要使用新的
PaisDTO(null, null, null)
实例化 PaisDTO,Jackson 将完成其工作并为您返回 {}
一个更简单的解决方案,没有任何额外的类或复杂性是使用地图:
return ResponseEntity.ok(Map.of());