Spring MVC returning JSONS and exception Handling

后端 未结 3 923
庸人自扰
庸人自扰 2021-02-06 07:33

I am using Spring MVC with Controllers, my question is how do I return a JSON response which is different from the @ResponseBody object which is returned and convereted to a JSO

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-06 08:30

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

    in your spring config :

    
    
        
            
            
        
    
    

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

    public class MyMessageConverter implements HttpMessageConverter {
    // 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.

    提交回复
    热议问题