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.

Featured

Learn Spring Framework today!

Take an online course and become a Spring Framework champion!

Here is what is covered:

  • The Spring Framework basics, including Spring MVC
  • How to work with JDBC and MySQL (in the context of Spring)
  • Build real applications step by step
  • A detailed walkthrough of Spring's core concepts
  • ... and much more!
Spring Framework logo
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!

One comment on »Returning Empty JSON Object in Spring Framework«

  1. Belal Juma

    Very helpful

    Thanks

Leave a Reply

Your e-mail address will not be published.