简体   繁体   English

Spring 引导:返回一个空的 JSON 而不是返回空体 object 是 null

[英]Spring Boot: Return a empty JSON instead of empty body when returned object is null

I have a RestController and when I call the method:我有一个 RestController,当我调用该方法时:

@RequestMapping(value = "/sigla/{sigla}")
@ResponseBody
public PaisDTO obterPorSigla(@PathVariable String sigla) {
    return service.obterPorSigla(sigla);
}

If a record is found, I get a good JSON response:如果找到记录,我会得到一个很好的 JSON 响应:

{"nome":"Brasil","sigla":"BR","quantidadeEstados":27}

but when nothing is found on database the RestController returns null and I get a empty response, completely blank body.但是当在数据库中找不到任何内容时,RestController 返回 null 并且我得到一个空的响应,完全是空白的主体。

How can I display a empty JSON instead of a blank response?如何显示空的 JSON 而不是空白响应? Like bellow:像下面这样:

{}

Complete Controller:完成 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);
    }

First, if you're using @RestController annotation you don't need the @ResponseBody annotation, get rid of that.首先,如果您使用@RestController批注,则不需要@ResponseBody批注,请摆脱它。

Second if you're trying to have REST Controller, then you're missing a few things, do it like this:其次,如果您尝试使用 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); 
}

In the example above if you'll get null then you'll return an empty response JSON.在上面的示例中,如果您将获得 null,那么您将返回一个空的响应 JSON。

The only way that I could find was to create an empty class我能找到的唯一方法是创建一个空类

@JsonSerialize
public class EmptyJsonBody {
}

Then add this to your response然后将此添加到您的回复中

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

Solution 1: You have to implement you entity class with Serializable Solution 2: Your class should have getter and setter In my case the getter and setter were given protected access modifiers.解决方案 1:您必须使用 Serializable 实现实体类 解决方案 2:您的类应该具有 getter 和 setter 在我的情况下,getter 和 setter 被赋予了受保护的访问修饰符。 so I changed them to public and vola it worked所以我把它们改成 public 和 vola 它起作用了

I am using this as suggested by marcos almedia..but I am getting java object hashcode response instead json empty {} response我按照 marcos almedia 的建议使用它..但我得到 java object 哈希码响应而不是 json 空 {} 响应

@JsonSerialize public class EmptyJsonBody {} @JsonSerialize 公共 class EmptyJsonBody {}

How can we resolve it?我们如何解决它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM