Spring Boot:当返回的对象为null时,返回空JSON而不是空体

时间:2017-06-30 02:49:43

标签: json spring rest

我有一个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);
    }

3 个答案:

答案 0 :(得分:3)

首先,如果您使用@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。

答案 1 :(得分:2)

我唯一能找到的方法就是创建一个空的类

@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());
    }
}

答案 2 :(得分:1)

解决方案1: 您必须使用Serializable实现您的实体类 解决方案2: 您的班级应该有getter和setter 就我而言,getter和setter被赋予了受保护的访问修饰符。所以我把它们改成了公开的,而且效果很好