FastJson : 阿里巴巴开源解析框架,是目前开源框架中json解析最快的。
导入依赖:引入spring boot 默认使用的 jackson 所以需要将该依赖移除
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 去除 jackson -->
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
配置FastJson Confog
/**
* 用于设置 fastjson 的 返回数据的格式设置
* @return
*/
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setCharset(Charset.forName("UTF-8"));
config.setDateFormat("yyyy-mm-dd");
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteClassName,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.PrettyFormat
);
converter.setFastJsonConfig(config);
return converter;
}
解释,用于设置日期返回的格式、数据编码、是否返回类名称、Map是否为空、List是都为空、json格式化、字符串输出为“” 而不是null
但是在配置完成上面配置之后,还需要配置一下响应的编码,否则返回的json 数据是乱码的
# 开启响应的编码 因为使用的是 fastjson 进行数据的响应
spring.http.encoding.force-response=true
当然上面是一种配置的方式,如果不使用上面的配置方式,可以使用下面的配置方式来进行fastjson 的配置,需要实现
WebMvcConfigurer 该类是spring mvc 最基本的配置,如果有什么需要自定义的配置,只要实现 WebMvcConfigurer 接口即可
(在spring 5.0 之前 是通过 继承 WebMvcAutoConfigurationAdapter 来实现的)
/**
* 用于设置 fastjson 的 返回数据的格式设置
* @return
*/
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setCharset(Charset.forName("UTF-8"));
config.setDateFormat("yyyy-mm-dd");
config.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteClassName,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.PrettyFormat
);
converter.setFastJsonConfig(config);
return converter;
}