SpringBoot(九):fastjson、异常处理

1、fastjson

  1. pom.xml加入jar
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.31</version>
    </dependency>
  2. 配置fastjson:继承WebMvcConfigurerAdapter覆写configureMessageConverters方法
    @Configuration
    public class SpringMVCConfig extends WebMvcConfigurerAdapter{
        @Override
        public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            FastJsonHttpMessageConverter4 fastJsonConverter = new FastJsonHttpMessageConverter4();
            converters.add(fastJsonConverter);
        }
    }

使用fastjson中注解@JSONField

@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date orderTime;

{
    "id": 1,
    "orderList": [
        {
            "id": 3,
            "orderMoney": 998,
            "orderTime": "2017-08-19 10:22:44",
            "userId": 1
        }
    ],
    "userName": "w"
}

关于另外一种配置fastjson方式

2、异常处理

补充:

       改用@ControllerAdvice

继承WebMvcConfigurerAdapter覆写configureHandlerExceptionResolvers方法

@Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                Result result  = new Result();
                if (ex instanceof BizException){
                    BizException bizException = (BizException)ex;
                    result.setCode(bizException.getErrorCode());
                    result.setMessaage(bizException.getMessage());
                }else{
                    result.setCode(-1);
                    result.setMessaage("系统异常,请联系管理员");
                }

                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-type", "application/json;charset=UTF-8");
                try {
                    response.getWriter().write(JSON.toJSONString(result));
                } catch (IOException e) {
                    LOG.info("异常处理获取输出流异常",e);
                    e.printStackTrace();
                }
                return new ModelAndView();
            }
        });
    }
{"code":1,"messaage":"业务校验不通过"}

 

猜你喜欢

转载自my.oschina.net/u/2526015/blog/1543440