Spring Boot 默認使用 Jackson 作為 JSON 處理器,但國內項目常使用阿里巴巴的 Fastjson,因其性能優異且功能豐富。本文介紹 Spring Boot 中集成 Fastjson 的兩種主流方式,以及常用配置技巧。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version> <!-- 建議使用較新版本 -->
</dependency>
適用場景:需要完全控制轉換器順序、自定義配置
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter { // Spring Boot 2.x 實現 WebMvcConfigurer 接口
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 1. 創建 Fastjson 轉換器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2. 配置 Fastjson 特性
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat, // 格式化輸出
SerializerFeature.WriteMapNullValue, // 輸出 null 值字段
SerializerFeature.WriteNullStringAsEmpty, // null 字符串輸出 ""
SerializerFeature.WriteNullListAsEmpty, // null 集合輸出 []
SerializerFeature.DisableCircularReferenceDetect // 禁用循環引用檢測(性能優化)
);
// 3. 日期格式統一
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastConverter.setFastJsonConfig(fastJsonConfig);
// 4. 添加到轉換器列表首位(優先使用)
converters.add(0, fastConverter);
}
}
適用場景:Spring Boot 2.x+,配置類分離,便於維護
@Configuration
public class FastJsonConfig {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1. 創建轉換器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2. 核心配置
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.DisableCircularReferenceDetect
);
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setCharset(StandardCharsets.UTF_8);
fastConverter.setFastJsonConfig(config);
// 3. 設置支持的 MediaType
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
fastConverter.setSupportedMediaTypes(supportedMediaTypes);
return new HttpMessageConverters(fastConverter);
}
}
| 特性 | 作用 |
|---|---|
| PrettyFormat | 美化輸出,帶縮進換行 |
| WriteMapNullValue | 輸出值為 null 的字段 |
| WriteNullStringAsEmpty | null 字符串輸出 "" |
| WriteNullListAsEmpty | null 集合輸出 [] |
| WriteNullNumberAsZero | null 數值輸出 0 |
| WriteNullBooleanAsFalse | null 布爾值輸出 false |
| DisableCircularReferenceDetect | 禁用循環引用檢測(提升性能,需確保無循環引用) |
| BrowserCompatible | 瀏覽器兼容模式(中文不轉 Unicode) |
在實體類字段上使用,精確控制序列化/反序列化行為:
public class User {
private Long id;
@JSONField(name = "user_name") // 指定 JSON key 名稱
private String username;
@JSONField(format = "yyyy-MM-dd") // 日期格式化
private Date birthday;
@JSONField(serialize = false) // 序列化時忽略(不輸出到 JSON)
private String password;
@JSONField(deserialize = false) // 反序列化時忽略(不從 JSON 讀取)
private String tempField;
@JSONField(ordinal = 1) // 輸出順序
private String email;
// getter/setter 省略
}
fastjson:
date-format: yyyy-MM-dd HH:mm:ss
charset: UTF-8
serializer-features:
- PrettyFormat
- WriteMapNullValue
- WriteNullStringAsEmpty
- WriteNullListAsEmpty
- DisableCircularReferenceDetect
parser-features:
- AllowArbitraryCommas
- AllowUnQuotedFieldNames
- IgnoreNotMatch
需配合 FastJsonConfig 類讀取配置屬性。
DisableCircularReferenceDetect 或使用 @JSONField(serialize=false) 打破環SerializerFeature.BrowserCompatible 或後端轉 String 輸出Spring Boot 集成 Fastjson 推薦使用 @Bean 方式,配置清晰、易維護。核心在於 FastJsonConfig 的特性設置,根據業務場景選擇合適的序列化特性。字段級別用 @JSONField 精確控制,全局統一用配置類管理。