Returning Empty JSON Object in Spring Framework

Published on February 17, 2015 by

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.

Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

4 comments on »Returning Empty JSON Object in Spring Framework«

  1. Belal Juma

    Very helpful

    Thanks

  2. Shariq

    I did not use @Jsonserialize yet I am getting response in json by just using ResponseEntity and RestController with Jackson in classpath

  3. ThetaSinner

    Hi,

    This is a really helpful tip.
    But I get a warning about unchecked types when I try to pass the ’empty json’ object to ResponseEntity.

    Instead you can remove the annotation from the EmptyJsonResponse, and just make it the @ResponseBody for your method.

  4. ThetaSinner

    Although I just noticed you can’t remove the @JsonSerialize when the object is empty :)
    Otherwise that works though

Leave a Reply

Your e-mail address will not be published.