Spring Boot USES FastJson to parse JSON data

  • 2020-06-12 09:15:54
  • OfStack

The most common json framework for personal use is fastjson, so spring boot's default json is unfamiliar, so naturally I thought, can I use fastjson for json parsing?

1. Introduction of fastjson dependency library:


<!-- add fastjson parsing JSON data -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.16</version>
</dependency>

2. Configuration fastjson

The official document says that after 1.2.10, there will be two methods to support HttpMessageconvert, one is FastJsonHttpMessageConverter, the other is FastJsonHttpMessageConverter4, and the other is FastJsonHttpMessageConverter4. The specific differences have not been studied in depth. The lower version is not supported, so the minimum requirement here is 1.2.10+

Method 1:

(1) The boot class inherits WebMvcConfigurerAdapter

(2) Overwrite method configureMessageConverters

Specific code:


@SpringBootApplication //  That let spring boot Automatically configuring the program as necessary is equivalent to using default properties @Configuration . @EnableAutoConfiguration and @ComponentScan
public class Application extends WebMvcConfigurerAdapter{

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);

    //  Initialization converter 
    FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
    //  Initialize the 1 Ten converter configuration 
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    //  Add configuration Settings to the converter HttpMessageConverter In the converter list 
    fastConvert.setFastJsonConfig(fastJsonConfig);

    converters.add(fastConvert);
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Method 2:

In the configuration or startup class, inject Bean: HttpMessageConverters


/**
* Bean Configuration management 
* Created by surpass.wei@gmail.com on 2017/2/21.
*/
@Configuration
public class BeanConfig {

 /* injection Bean : HttpMessageConverters To support fastjson*/
 @Bean
 public HttpMessageConverters fastJsonHttpMessageConverters() {
   FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
   FastJsonConfig fastJsonConfig = new FastJsonConfig();
   fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
   fastConvert.setFastJsonConfig(fastJsonConfig);
   return new HttpMessageConverters((HttpMessageConverter<?>) fastConvert);
 }
}

Configuration is completed, use in entity class @ JSONField (serialize = false), if the field is not returned, if it is, so congratulations you configure a success, including JSONField package path is: com. alibaba. fastjson. annotation. JSONField


Related articles: