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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。