我有一个RestController,当我调用该方法时:
@RequestMapping(value = "/sigla/{sigla}")
@ResponseBody
public PaisDTO obterPorSigla(@PathVariable String sigla) {
return service.obterPorSigla(sigla);
}
Run Code Online (Sandbox Code Playgroud)
如果找到记录,我会得到一个好的JSON响应:
{"nome":"Brasil","sigla":"BR","quantidadeEstados":27}
Run Code Online (Sandbox Code Playgroud)
但是当在数据库中找不到任何内容时,RestController返回null并且我得到一个空响应,完全空白的主体.
如何显示空JSON而不是空白响应?如下:
{}
Run Code Online (Sandbox Code Playgroud)
完整控制器:
@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);
}
Run Code Online (Sandbox Code Playgroud)
小智 16
解决方案 1:您必须使用可序列化来实现实体类 解决方案 2:您的类应该具有 getter 和 setter 在我的例子中,getter 和 setter 被赋予了受保护的访问修饰符。所以我把它们改为公开的,vola 成功了
我能找到的唯一方法是创建一个空类
@JsonSerialize
public class EmptyJsonBody {
}
Run Code Online (Sandbox Code Playgroud)
然后将其添加到您的回复中
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
首先,如果您使用的@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);
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,如果您将获得 null,那么您将返回一个空的响应 JSON。
| 归档时间: |
|
| 查看次数: |
14478 次 |
| 最近记录: |