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.
8 comments on »Returning Empty JSON Object in Spring Framework«
Very helpful
Thanks
I did not use @Jsonserialize yet I am getting response in json by just using ResponseEntity and RestController with Jackson in classpath
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.
Although I just noticed you can’t remove the @JsonSerialize when the object is empty :)
Otherwise that works though
What about if you are using kotlin as language
Hello Sir
Please any idea for this issue the application create table in database but the Json object return is empty [{},{},{}]
@RestController
@RequestMapping(“/api/v3”)
public class ExpenController {
@Autowired
ExpenseService expenService;
@GetMapping(“/exp”)
public ResponseEntity<List> get(){
List expenses = expenService.findAll();
return new ResponseEntity<List>(expenses,HttpStatus.OK);
} }
———————————————————
@Service
public class ExpenseServiceImpl implements ExpenseService {
@Autowired
ExpenRepository expenRepository;
@Override
public List findAll() {
return expenRepository.findAll() ;
}
}
usefull, thank you
Hello Amanullah AHMADZAI
just add setter ng getter in your entity class