Spring Boot JSON序列化优化:Gson配置全攻略
你还在为Spring Boot默认JSON处理器的性能问题烦恼吗?还在纠结如何自定义日期格式、排除敏感字段?本文将带你5分钟搞定Gson与Spring Boot的无缝集成,从依赖配置到高级定制,让你的API返回更优雅的JSON数据。
读完本文你将掌握:
- 快速替换Spring Boot默认JSON处理器为Gson
- 自定义日期格式化、字段命名策略
- 排除敏感字段和空值的实用技巧
- 全局Gson配置与局部注解的灵活应用
为什么选择Gson?
Gson(JSON序列化/反序列化库)是Google开发的Java JSON处理工具,相比Spring Boot默认的Jackson,它具有更简洁的API、更强的类型适配能力和更好的性能表现。根据Gson性能测试显示,在处理大型集合序列化时,Gson性能比Jackson提升约15-20%。
快速集成步骤
1. 添加Gson依赖
在pom.xml中添加Gson依赖,同时排除Spring Boot默认的Jackson:
<dependencies>
<!-- 排除默认Jackson依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加Gson依赖 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
2. 配置GsonHttpMessageConverter
创建Gson配置类,自定义序列化规则:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
public class GsonConfig {
@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter() {
// 创建Gson构建器
GsonBuilder gsonBuilder = new GsonBuilder();
// 配置日期格式化
gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
// 自定义LocalDateTime序列化
gsonBuilder.registerTypeAdapter(LocalDateTime.class,
(jsonSerializer, type, jsonSerializationContext) ->
new JsonPrimitive(jsonSerializer.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)));
// 排除null值字段
gsonBuilder.serializeNulls(false);
// 设置字段命名策略(驼峰转下划线)
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// 创建Gson实例
Gson gson = gsonBuilder.create();
// 创建并返回Gson消息转换器
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
}
核心配置详解
GsonBuilder常用配置
| 配置方法 | 功能描述 |
|---|---|
setDateFormat(String pattern) | 设置全局日期格式化模式 |
serializeNulls() | 序列化null值字段 |
excludeFieldsWithModifiers(int... modifiers) | 排除指定修饰符的字段 |
setFieldNamingPolicy(FieldNamingPolicy policy) | 设置字段命名策略 |
setPrettyPrinting() | 启用JSON美化输出 |
registerTypeAdapter(Type type, Object typeAdapter) | 注册自定义类型适配器 |
字段命名策略对比
Gson提供多种字段命名策略,可通过FieldNamingPolicy选择:
IDENTITY: 保持字段原名(默认)LOWER_CASE_WITH_UNDERSCORES: 驼峰转下划线(如userName→user_name)UPPER_CAMEL_CASE: 首字母大写(如userName→UserName)LOWER_CASE_WITH_DASHES: 驼峰转连字符(如userName→user-name)
高级应用技巧
1. 排除敏感字段
使用@Expose注解精细控制字段序列化:
import com.google.gson.annotations.Expose;
public class User {
@Expose(serialize = true, deserialize = true)
private String username; // 序列化和反序列化
@Expose(serialize = false)
private String password; // 仅反序列化
private String internalCode; // 不序列化也不反序列化
}
在GsonBuilder中启用@Expose支持:
gsonBuilder.excludeFieldsWithoutExposeAnnotation();
2. 自定义类型适配器
以LocalDateTime序列化为例,创建自定义适配器:
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeAdapter extends TypeAdapter<LocalDateTime> {
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public void write(JsonWriter out, LocalDateTime value) throws IOException {
out.value(value.format(FORMATTER));
}
@Override
public LocalDateTime read(JsonReader in) throws IOException {
return LocalDateTime.parse(in.nextString(), FORMATTER);
}
}
注册适配器:
gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter());
3. 全局配置与局部注解结合
全局配置基础上,可使用@SerializedName注解为特定字段指定别名:
import com.google.gson.annotations.SerializedName;
public class Order {
@SerializedName("order_id")
private Long id;
@SerializedName(value = "create_time", alternate = {"created_at"})
private LocalDateTime createTime;
}
常见问题解决
日期格式化不一致
问题:不同实体类日期格式需求不同
解决:全局配置默认格式,特殊字段使用@JsonAdapter注解指定适配器:
import com.google.gson.annotations.JsonAdapter;
public class Product {
private String name;
@JsonAdapter(DateTimeAdapter.class) // 使用特定适配器
private LocalDateTime productionDate;
}
循环引用导致栈溢出
问题:实体类存在双向引用时序列化失败
解决:使用@Expose排除一方引用或配置排除策略:
gsonBuilder.addSerializationExclusionStrategy((fieldAttributes) ->
fieldAttributes.getName().equals("parent") // 排除parent字段
);
总结与最佳实践
- 依赖管理:始终使用最新稳定版Gson,避免版本冲突
- 配置分离:简单配置用
application.properties,复杂配置用Java Config - 性能优化:对高频使用的类型注册专用TypeAdapter
- 安全考虑:生产环境禁用
setPrettyPrinting(),减少网络传输量 - 测试验证:使用GsonTest验证自定义配置
通过本文介绍的方法,你已经掌握了Gson与Spring Boot集成的全部技巧。无论是简单的日期格式化还是复杂的类型适配,Gson都能满足你的需求。开始优化你的API返回格式,给用户更友好的JSON体验吧!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



