Spring Boot integration fastjson

table of Contents

 

The introduction of dependence

Springboot1.x version

The first method: the method and implemented by rewriting configureMessageConverters extends WebMvcConfigurerAdapter.

The second method: @Bean project startup class

Springboot2.0 version


The introduction of dependence

Note that the following serious risk vulnerabilities 1.2.61, 1.2.61 fixes, you must upgrade to 1.2.61, the latest version is 1.2.62

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

Springboot1.x version

The first method: the method and implemented by rewriting configureMessageConverters extends WebMvcConfigurerAdapter.


 
import java.util.List;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@MapperScan("com.example.demo.mapper")
@SpringBootApplication(scanBasePackages= {"com.example.demo.controller","com.example.demo.service"})
public class HelloSpringBootApplication extends WebMvcConfigurerAdapter{
 
 
 
 @Override
 public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  
  //创建FastJson的消息转换器
  FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
  //创建FastJson的配置对象
  FastJsonConfig config = new FastJsonConfig();
  //对Json数据进行格式化
  config.setSerializerFeatures(SerializerFeature.PrettyFormat);
  convert.setFastJsonConfig(config);
  converters.add(convert);
 }
 
 
 
 public static void main(String[] args) {
  
  SpringApplication.run(HelloSpringBootApplication.class, args);
 }
 
}

The second method: @Bean project startup class

package com.example.demo;
 
import java.util.List;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@MapperScan("com.example.demo.mapper")
@SpringBootApplication(scanBasePackages= {"com.example.demo.controller","com.example.demo.service"})
public class HelloSpringBootApplication
{
 
 
 
 
 @Bean
 public HttpMessageConverters fastJsonMessageConverter() {
  
    //创建FastJson的消息转换器
    FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
    //创建FastJson的配置对象
    FastJsonConfig config = new FastJsonConfig();
    //对Json数据进行格式化
    config.setSerializerFeatures(SerializerFeature.PrettyFormat);
    convert.setFastJsonConfig(config);
    HttpMessageConverter<?> con =convert;
    return new HttpMessageConverters(con);
 }
 
 public static void main(String[] args) {
  
  SpringApplication.run(HelloSpringBootApplication.class, args);
 }
 
}

Springboot2.0 version

package com.example.fast;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lupenghu
 * @Des
 * @Date create in 17:002020/1/6
 */
@Configuration
public class JsonConfig implements WebMvcConfigurer {
    /**
     * 使用fastjson代替jackson
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        /*
         先把JackSon的消息转换器删除.
         备注: (1)源码分析可知,返回json的过程为:
                    Controller调用结束后返回一个数据对象,for循环遍历conventers,找到支持application/json的HttpMessageConverter,然后将返回的数据序列化成json。
                    具体参考org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor的writeWithMessageConverters方法
               (2)由于是list结构,我们添加的fastjson在最后。因此必须要将jackson的转换器删除,不然会先匹配上jackson,导致没使用fastjson
        */
        for (int i = converters.size() - 1; i >= 0; i--) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.remove(i);
            }
        }
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        //自定义fastjson配置
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                SerializerFeature.WriteMapNullValue,        // 是否输出值为null的字段,默认为false,我们将它打开
                SerializerFeature.WriteNullListAsEmpty,     // 将Collection类型字段的字段空值输出为[]
                SerializerFeature.WriteNullStringAsEmpty,   // 将字符串类型字段的空值输出为空字符串
                SerializerFeature.WriteNullNumberAsZero,    // 将数值类型字段的空值输出为0
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect    // 禁用循环引用
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(config);

        // 添加支持的MediaTypes;不添加时默认为*/*,也就是默认支持全部
        // 但是MappingJackson2HttpMessageConverter里面支持的MediaTypes为application/json
        // 参考它的做法, fastjson也只添加application/json的MediaType
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        converters.add(fastJsonHttpMessageConverter);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> messageConverter : converters) {
            System.out.println("=====================" + messageConverter);
        }
    }
}

test

@RestController
public class TestController {
    @RequestMapping("/test")
    public Object test() {
        User user = new User();
        user.date = new Date();
        user.name = "王章";
        return user;
    }
}

public class User {
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    public Date date;
    public String name;
}

 

 

Published 260 original articles · won praise 112 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_34491508/article/details/103857133