【教程】fastjson升级,spring boot设置fastjson2做序列化反序列化

2年前 (2022) 程序员胖胖胖虎阿
209 0 0

FastJsonHttpMessageConverter

一、简介

项目地址

为什么要升级? 官方给出的对比

fastjson2并非常规升级,可以说是一次重构。fastjson2更快,更安全

二、如何升级?

2.1 替换maven和包名

如果代码中没有过多的直接使用FastJson的类,直接替换maven和.java文件中的包名即可

建议大家不要直接使用Json类,而是自己封装一个json类,这样当出现问题时,也好改,避免每次都去修改大量的文件

2.2 修改SpringBoot MessageConverters

spring boot默认的消息转换中,json的序列化和反序列化是jackson

如果你在fastjson 1配置了消息转换,升级到fastjson2,你需要引入fastjson2-extension,并且FastJsonHttpMessageConverter的包名为

com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter

完整的配置文件(博主当前是spring boot 2.6.7)

<!-- pom.xml -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 去掉Jackson依赖,用fastjson -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>${fastjson2.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2-extension</artifactId>
            <version>${fastjson2.version}</version>
        </dependency>
// 和fastjson 1一样,只是包路径变了
// import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;

@Configuration
public class JsonMessageConverterConfigurer implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 自定义配置...
        // FastJsonConfig config = new FastJsonConfig();
        // config.set...
        // converter.setFastJsonConfig(config);

        // spring boot高版本无需配置,低版本不配置报错:Content-Type cannot contain wildcard type '*'
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(fastMediaTypes);

        converters.add(0,converter);
    }
}

相关文章

暂无评论

暂无评论...