SpringBoot(九):fastjson、异常处理

僤鯓⒐⒋嵵緔 提交于 2020-03-24 19:33:09

3 月,跳不动了?>>>

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":"业务校验不通过"}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!