Spring MVC returning JSONS and exception Handling Spring MVC returning JSONS and exception Handling json json

Spring MVC returning JSONS and exception Handling


Create a response class:

public class Response<T> {    T data;    boolean status = true;    public Response(T d) { data = d; }}

Then return that from your controllers:

@ResponseBody public Response getUserDetails) {    //...    return new Response(userDetails);}

For the exception you'll want to return an object like:

public class BadStatus {    String errorMessage;    boolean status = false;    public BadStatus(String msg) { errorMessage = msg; }}@ExceptionHandler(Exception.class)public BadStatus handleException(Exception ex, HttpServletRequest request) {  return new BadStatus(ex.getMessage());}


Yes. Return a model and a view instead.

public ModelMap getUserDetails() {    UserDetails userDetails; // get this object from somewhere    ModelMap map = new ModelMap()(;    map.addAttribute("data", userDetails);    map.addAttribute("success", true);    return map;}

To add the exception you'd do it the same way with a key and success = false.


An alternate solution (works with spring 3.1), which is less invasive

in your spring config :

<bean id="jacksonConverter"     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /><mvc:annotation-driven>    <mvc:message-converters>        <bean class="mypackage.MyMessageConverter"            p:delegate-ref="jacksonConverter">        </bean>    </mvc:message-converters></mvc:annotation-driven>

The idea is to provide your own HttpMessageConverter that delegates to the provided jackson converter.

public class MyMessageConverter implements HttpMessageConverter<Object> {// setters and delegating overrides ommitted for brevity@Override    public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException,            HttpMessageNotWritableException {// t is whatever your @ResponseBody annotated methods return        MyPojoWrapper response = new MyPojoWrapper(t);        delegate.write(response, contentType, outputMessage);    }}

This way all your pojos are wrapped with some other json that you provide there.

For exceptions, the solution proposed by ericacm is the simplest way to go (remember to annotate the 'BadStatus' return type with @ResponseBody).

A caveat : your json-serialized BadStatus goes through MyMessageConverter too, so you will want to test for the object type in the overriden 'write' method, or have MyPojoWrapper handle that.