Springboot替换默认jackSon为fastJson过程

柔光的暖阳◎ 2022-03-19 10:44 333阅读 0赞

因为工作原因,需要将jackJson替换为fastJson。
先说过程Springboot2.0以前的写法:

第一种:通过在启动类中实现WebMvcConfigurerAdapter 并重写ConfigureMessageConverters方法

第一步: pom.xml 中引用fastjson

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.45</version>
  5. </dependency>

第二步: 启动类中配置

  1. @SpringBootApplication //申明让spring boot自动给程序进行必要的配置
  2. public class AppStart extends WebMvcConfigurerAdapter {
  3. public static void main(String[] args) {
  4. SpringApplication.run(AppStart.class, args);
  5. }
  6. @Override
  7. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  8. super.configureMessageConverters(converters);
  9. FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
  10. FastJsonConfig fastJsonConfig = new FastJsonConfig();
  11. fastJsonConfig.setSerializerFeatures(
  12. SerializerFeature.PrettyFormat,
  13. SerializerFeature.WriteMapNullValue,
  14. SerializerFeature.WriteNullNumberAsZero,
  15. SerializerFeature.WriteNullStringAsEmpty
  16. );
  17. // 处理中文乱码问题
  18. List<MediaType> fastMediaTypes = new ArrayList<>();
  19. fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  20. fastConverter.setSupportedMediaTypes(fastMediaTypes);
  21. fastConverter.setFastJsonConfig(fastJsonConfig);
  22. //处理字符串, 避免直接返回字符串的时候被添加了引号
  23. StringHttpMessageConverter smc = new StringHttpMessageConverter(Charset.forName("UTF-8"));
  24. converters.add(smc);
  25. converters.add(fastConverter);
  26. }
  27. }

第二种:通过在启动类中配置JavaBean

在启动类中直接以JavaBean的形式进行配置

  1. @SpringBootApplication //申明让spring boot自动给程序进行必要的配置
  2. public class AppStart extends WebMvcConfigurerAdapter {
  3. @Bean
  4. public HttpMessageConverters fastJsonHttpMessageConverters() {
  5. // 1.定义一个converters转换消息的对象
  6. FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
  7. // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据
  8. FastJsonConfig fastJsonConfig = new FastJsonConfig();
  9. fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
  10. // 3.在converter中添加配置信息
  11. fastConverter.setFastJsonConfig(fastJsonConfig);
  12. // 4.将converter赋值给HttpMessageConverter
  13. HttpMessageConverter<?> converter = fastConverter;
  14. // 5.返回HttpMessageConverters对象
  15. return new HttpMessageConverters(converter);
  16. }
  17. public static void main(String[] args) {
  18. SpringApplication.run(AppStart.class, args);
  19. }
  20. }

Springboot2.0以后,WebMvcConfigurerAdapter 过时了,原因是Springboot2.0最低支持JDK1.8,引入了新的default关键字,该关键字配置在interface接口的方法时子类可以不去实现该方法,相当于抽象类内已经实现的接口方法。新的代替方法是:直接实现WebMvcConfigurer或者实现WebMvcConfigurationSupport

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读