栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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)


        
            org.springframework.boot
            spring-boot-starter-web
            
                
                
                    org.springframework.boot
                    spring-boot-starter-json
                
            
        


        
            com.alibaba.fastjson2
            fastjson2
            ${fastjson2.version}
        

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

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

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

        converters.add(0,converter);
    }
}



往期好文推荐:
如何在家搭建服务器?如何在公网访问家庭内的设备?如何满带宽 + 无需公网服务器地进行内net川透?
博主的答案:《NameSilo的DDNS动态域名解析脚本》

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929954.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号