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

描述

原来环境

Spring boot1.5.3spring

fastjsonjson

<!--阿里 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三种解析框架的区别。code

参考连接orm

https://www.jianshu.com/p/45c603e34203
相关文章
相关标签/搜索