首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 集成 Fastjson 實現 JSON 序列化與反序列化完整指南

     編輯:Java 相關知識

前言

Spring Boot 默認使用 Jackson 作為 JSON 處理器,但國內項目常使用阿里巴巴的 Fastjson,因其性能優異且功能豐富。本文介紹 Spring Boot 中集成 Fastjson 的兩種主流方式,以及常用配置技巧。

依賴引入

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version> <!-- 建議使用較新版本 -->
</dependency>

方式一:繼承 WebMvcConfigurer 重寫 configureMessageConverters

適用場景:需要完全控制轉換器順序、自定義配置

@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);
    }
}

方式二:@Bean 注入 HttpMessageConverters(推薦,更簡潔)

適用場景: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);
    }
}

常用 SerializerFeature 詳解

特性作用
PrettyFormat美化輸出,帶縮進換行
WriteMapNullValue輸出值為 null 的字段
WriteNullStringAsEmptynull 字符串輸出 ""
WriteNullListAsEmptynull 集合輸出 []
WriteNullNumberAsZeronull 數值輸出 0
WriteNullBooleanAsFalsenull 布爾值輸出 false
DisableCircularReferenceDetect禁用循環引用檢測(提升性能,需確保無循環引用)
BrowserCompatible瀏覽器兼容模式(中文不轉 Unicode)

字段級別控制:@JSONField 註解

在實體類字段上使用,精確控制序列化/反序列化行為:

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 省略
}

全局配置屬性(application.yml)

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 類讀取配置屬性。

避坑指南

  • 版本選擇:建議使用 1.2.80+ 版本,修復了多個安全漏洞
  • 循環引用:實體類雙向關聯時必須配置 DisableCircularReferenceDetect 或使用 @JSONField(serialize=false) 打破環
  • Long 類型精度丟失:JS 前端處理 Long 會精度丟失,建議配置 SerializerFeature.BrowserCompatible 或後端轉 String 輸出
  • 與 Jackson 共存:若項目同時需要兩者,需明確配置轉換器順序,避免衝突

總結

Spring Boot 集成 Fastjson 推薦使用 @Bean 方式,配置清晰、易維護。核心在於 FastJsonConfig 的特性設置,根據業務場景選擇合適的序列化特性。字段級別用 @JSONField 精確控制,全局統一用配置類管理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved