精益编程框架

开发文档
点击登录,精彩内容等着你
-

Springboot使用Fastjson2转换器

系列文档

关联类名: JSONWebMvcConfigurer.javaJSONObject.javaJSONArray.java

JSONWebMvcConfigurer的配置,作为springboot引入Fastjson2的重要配置步骤,其作用为


  • 自动配置MessageConverter,使用Fastjson2相应的转换器
  • 增加对Fastjson2的配置,包括时间格式,转换特性Feature等

关于springboot如何介入Fastjson2,请移步Fastjson2让springboot的json序列化飞起来


关键字:Fastjson2,springboot的Fastjson2序列化与反序列化
关联类:com.alibaba.fastjson2,JSONWebMvcConfigurer.java

一、JSONWebMvcConfigurer.java

使用注解:@Configuration,让spring的自动配置自动扫描该类,在项目启动的时候,能配置相应的Bean或者组件(这里就是转换器)

注意:

  1. @Configuration依靠着spring的@ServletComponentScan的扫描包路径配置
  2. @ServletComponentScan的包路径配置为空是,默认为启动类所在的包路径下,如启动类位于com包下,代表com.下所有的注解将全面进行扫描
  3. spring中有多种消息,如:一般的javabean的json操作,spring web view,redis的json转换,springboot web socket等,不同的消息类型,有着不同的转换器配置方式:

1. FastJsonConfig配置

该配置,设置全局fastjson2的转换规则

  1. @Bean
  2. public FastJsonConfig fastJsonConfig() {
  3. //1.自定义配置...
  4. FastJsonConfig config = new FastJsonConfig();
  5. config.setDateFormat("yyyy-MM-dd HH:mm:ss");
  6. //2.1配置序列化的行为
  7. //JSONWriter.Feature.PrettyFormat:格式化输出
  8. config.setWriterFeatures(JSONWriter.Feature.PrettyFormat);
  9. //2.2配置反序列化的行为
  10. config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
  11. return config;
  12. }

其中关注的是:WriterFeatures与ReaderFeatures的配置,基本以上配置就比较符合,其他属性配置,请参考官方文档

1.FastJsonHttpMessageConverter

使用 FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter
以提高 @RestController @ResponseBody @RequestBody 注解的 JSON序列化和反序列化速度。

  1. @Override
  2. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  3. //1.转换器
  4. FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
  5. converter.setDefaultCharset(StandardCharsets.UTF_8);
  6. converter.setFastJsonConfig(fastJsonConfig()); converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
  7. converters.add(0, converter);
  8. }

2.FastJsonJsonView

使用 FastJsonJsonView 来设置 Spring MVC 默认的视图模型解析器,如thymeleaf,jsp,freemarker
以提高 @Controller @ResponseBody ModelAndView JSON序列化速度。

  1. @Override
  2. public void configureViewResolvers(ViewResolverRegistry registry) {
  3. FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
  4. fastJsonJsonView.setFastJsonConfig(fastJsonConfig());
  5. registry.enableContentNegotiation(fastJsonJsonView);
  6. }

3.redis中使用Fastjson2序列化

redis进行缓存数据,或者缓存数据提取,转化为javabean或json时候,都需要一定的转换器来规范转换行为,
本章将不讨论次内容,请移步文档:自定义RedisTemplate的序列化..