1. 程式人生 > >spring boot 二 整合 FastJson

spring boot 二 整合 FastJson

1、在 pom.xml 導包 (必須高於 1.2.10 版本)

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

2、在 Spring boot 啟動類配置 Json解析。(配置方法有兩種)
第一種 (繼承 WebMvcConfigurerAdapter 重寫 configureMessageConverters方法 新增 FastJson 到 converters中)

@SpringBootApplication
public class App extends WebMvcConfigurerAdapter{

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //建立 FastJson
        FastJsonHttpMessageConverter fastConverter = new
FastJsonHttpMessageConverter(); FastJsonConfig fastConfig = new FastJsonConfig(); //配置 FastJson 基本設定 fastConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastConverter.setFastJsonConfig(fastConfig); //配置 FastJson 到 Spring boot中。 converters.add(fastConverter); } public
static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

方法二 @Bean 注入方式:(簡單,直接注入 FastJson 到 HttpMessageConverters 中)

@SpringBootApplication
public class App{

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverter(){
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastConfig = new FastJsonConfig();
        fastConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastConverter.setFastJsonConfig(fastConfig);

        return new HttpMessageConverters((HttpMessageConverter)fastConverter);
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}