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);
}
}
本文介绍如何在SpringBoot项目中集成阿里巴巴FastJSON库,并提供两种配置方法:通过继承WebMvcConfigurerAdapter重写方法和使用@Bean注入方式。
4060

被折叠的 条评论
为什么被折叠?



