Spring MVC returning JSONS and exception Handling

后端 未结 3 922
庸人自扰
庸人自扰 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:21

    Create a response class:

    public class Response {
        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());
    }
    

提交回复
热议问题