23

I have a RestController and when I call the method:

@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:

{"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.

How can I display a empty JSON instead of a blank response? Like bellow:

{}

Complete 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);
    }
1
  • can you be more specific about what you mean by an empty JSON? the response {} does not make any sense. Either the object in question has attributes (which can be blank/null) or it does not have attributes. If it has no attributes (and hence no values) then a blank/empty body would be the correct response. If the attributes exist but they are blank/null then initialize them as such Commented Jul 1, 2017 at 3:55

5 Answers 5

18

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. so I changed them to public and vola it worked

Sign up to request clarification or add additional context in comments.

2 Comments

I was getting empty response even though there was data. After reading your answer, I realized, I forgot to add getters/setters. Thanks it worked after that
In my case I was using a kotlin data entity object that had private fields. Like @priyankagoel simply removing the private field modifier (I opted to restrict the fields with internal modifier) fixed this for more, of cause with kotlin data generating the getters and setters for free
13

First, if you're using @RestController annotation you don't need the @ResponseBody annotation, get rid of that.

Second if you're trying to have REST Controller, then you're missing a few things, do it like this:

@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.

9 Comments

Hi Moshe, I've tried but still getting a empty body response when null and a fine response when there's object. I will edit my question including all the Controller.
Sorry, I missed the last close bracket }
No @Moshe Arad. Not yet.
What is missing? are you trying return null or just {} empty json?
It's working now. I want to return {}. What you answered was very important, so I joined your answer with another solution and solved. Basically I used your RestController model and instead of return ResponseEntity<>(headers, HttpStatus.OK); when null, I returned a empty class (withou any attribuites or methods) annotated with @JsonSerialize.
|
9

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

Comments

3

a much simpler solution without any additional class or complexity is using a map:

return ResponseEntity.ok(Map.of());

Comments

0

You can annotate PaisDTO class with @JsonInclude(Include.NON_NULL) annotation

@JsonInclude(Include.NON_NULL)
public record PaisDTO{
...
}

then when you get no results you just need to instantiate PaisDTO with new PaisDTO(null, null, null) and Jackson will do its job and return {} for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.