Returning Empty JSON Object in Spring Framework

Sometimes you may want to return an empty JSON object from a Spring Framework controller action, be it in a REST API or just a regular controller action. This could for example be the case if you are issuing an AJAX request from jQuery; if you specify the data type to be JSON, the success handler will not be invoked if there is no response body, because the response body does not contain valid JSON. Therefore it may be desirable to simply return {}.

Assuming that you have the Jackson JSON library on your classpath, this can be achieved with the following code.

The concept is to simply annotate a class with Jackson’s @JsonSerialize annotation. Since we do not want any fields/properties in the response, we will just leave the class empty.

@JsonSerialize
public class EmptyJsonResponse { }

Now we can use this class together with Spring Framework’s ResponseEntity class.

@RestController
public class CompanyController {
    @RequestMapping(value = "/api/something", method = RequestMethod.GET)
    public ResponseEntity something() {
        return new ResponseEntity(new EmptyJsonResponse(), HttpStatus.OK);
    }
}

Alternatively, one could use the @ResponseBody annotation above the method instead of annotating one’s controller with @RestController. The latter annotation is simply a convenient way of doing this for all controller actions.

That’s all there is to do. The above endpoint will return 200 OK and {} as the response body.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *