wybourn wybourn - 1 year ago 158
Java Question

Spring Controller always produce json

Is there anyway to force spring to always produce json, even an empty json object if there's no data to return.
Our services go through another service that rejects any response that isn't valid json (regardless of status code). It's not nice but we have no control of this.

With spring controllers you can tell them to produce json, but this only works when there's content to return. Is there a quick and elegant way to make all responses be json?

@RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> test(){
// if this returns null or an empty string the response body will be emtpy
// and the content-type header will not be set.
return service.getData();

The simply fix here is to simply add an if statement to check for null. But that's ugly as I'll have to manually set the header and the response body.

I'm hoping someone knows of a nicer way?


Answer Source

If you want all responses to return application/json, then you can set this at a single place by overriding postHandle() from HandlerInterceptorAdapter:

public class ResponseInterceptor extends HandlerInterceptorAdapter {

    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
            final ModelAndView modelAndView) throws IOException {
         if (response.getContentType() == null || response.getContentType().equals("")) {

You can look here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download