SpringBoot版本升级引起数据显示出错及排查

描述

原来环境

Spring boot1.5.3

fastjson

<!--阿里 FastJson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

pojo中配置

import com.alibaba.fastjson.annotation.JSONField;
import org.springframework.format.annotation.DateTimeFormat;

 	@JSONField(format = "yyyy-MM-dd HH:mm")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
    private Date pubTime;

测试结果

"pubTime": "2019-02-19 13:45",

升级2.0.6测试结果

"pubTime": "2019-02-26T09:22:24.000+0000",

排查解决

经过来回更换版本等几个小时的尝试后,分析结果:Spring Boot默认采用jackson作为解析,原因可能是采用1.5.3时,WebMvcConfigurer extends WebMvcConfigurerAdapter类中关于fastjson的配置起了作用,解析框架采用了fastjson(@JSONField);而升级为2.0.6之后,由于没有对WebMvcConfigurer配置(原WebMvcConfigurerAdapter上自动加了删除线),Spring boot默认采用了jackjson解析框架,导致@JSONField未起作用,故出现上述解析结果。

解决方案

就是要自己定义解析框架fastjson,不用Spring boot默认的jackson框架。

在启动类中添加以下配置:

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;

	@Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //创建FastJson信息转换对象
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        //创建Fastjosn对象并设定序列化规则
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 中文乱码解决方案
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);//设定json格式且编码为UTF-8
        fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypes);

        //规则赋予转换对象
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }

问题得到解决,时间格式可以正常返回显示。

拓展学习

掌握jackson、fastjson与gson三种解析框架的区别。

参考链接

https://www.jianshu.com/p/45c603e34203

转载于:https://my.oschina.net/u/3193075/blog/3071592

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值