Spring Boot中指定JSON序列化与反序列化的全面指南**
在Spring Boot应用中,JSON作为数据交换的格式无处不在,与前端交互、调用外部服务、存储数据等都离不开JSON,Spring Boot默认使用Jackson库来处理JSON的序列化(对象转JSON)和反序列化(JSON转对象),但在实际开发中,我们常常需要自定义JSON的格式,例如日期格式、字段命名策略、忽略特定字段、自定义序列化器等,本文将详细介绍Spring Boot中指定JSON配置的各种方法。
基于注解的局部配置(最常用)
注解方式灵活且粒度细,可以针对特定的类或字段进行JSON配置,无需影响全局。
-
@JsonFormat- 控制日期/时间格式 这是处理日期时间格式最常用的注解,它可以标注在日期时间类型的字段上,指定其序列化和反序列化的格式。import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class User { private String name; private Integer age; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; // getters and setters }pattern: 指定日期时间的格式模式。timezone: 指定时区,避免时区转换问题。
-
@JsonProperty- 指定JSON字段名 当Java对象的属性名与JSON中的字段名不一致时,使用此注解进行映射。import com.fasterxml.jackson.annotation.JsonProperty; public class User { @JsonProperty("user_name") private String name; @JsonProperty("user_age") private Integer age; // getters and setters }序列化后的JSON可能为:
{"user_name":"张三","user_age":25} -
@JsonIgnore- 忽略字段 如果某个字段不希望被序列化或反序列化到JSON中,可以使用@JsonIgnore。import com.fasterxml.jackson.annotation.JsonIgnore; public class User { private String name; private Integer age; @JsonIgnore private String password; // 密码不会被序列化到JSON // getters and setters } -
@JsonIgnoreProperties- 忽略未知属性 在反序列化时,如果JSON中包含了Java类中不存在的属性,默认会抛出异常,使用@JsonIgnoreProperties可以忽略这些未知属性。import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class User { private String name; private Integer age; // getters and setters }这样,即使JSON中有额外的字段(如"address"),也不会报错。
-
@JsonNaming- 指定属性命名策略 可以在类级别使用@JsonNaming来指定整个类的属性命名策略,例如驼峰命名转下划线命名。import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.annotation.JsonNaming; @JsonNaming(PropertyNamingStrategies.SnakeCase.class) public class User { private String userName; // 会被序列化为 user_name private Integer userAge; // 会被序列化为 user_age // getters and setters } -
@JsonSerialize和@JsonDeserialize- 自定义序列化/反序列化器 当内置的序列化/反序列化方式无法满足复杂需求时,可以自定义序列化器和反序列化器,并通过这两个注解指定。// 自定义序列化器示例 public class CustomDateSerializer extends StdSerializer<Date> { // 实现序列化逻辑 } // 自定义反序列化器示例 public class CustomDateDeserializer extends StdDeserializer<Date> { // 实现反序列化逻辑 } public class User { // ... 其他字段 @JsonSerialize(using = CustomDateSerializer.class) @JsonDeserialize(using = CustomDateDeserializer.class) private Date customDate; // getters and setters }
全局配置
如果希望某些配置对所有JSON处理生效,可以通过全局配置实现。
-
配置
ObjectMapperObjectMapper是Jackson的核心类,Spring Boot会自动配置一个ObjectMapperbean,我们可以通过自定义配置来修改它。在Spring Boot 2.x及以后,推荐使用
Jackson2ObjectMapperBuilderCustomizer来定制ObjectMapper:import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.context.annotation.Bean; import org.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { // 日期格式化 builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 注册JavaTimeModule,以支持Java 8的日期时间类型 builder.modules(new JavaTimeModule()); // 禁用默认的日期序列化方式(时间戳) builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 其他全局配置... }; } // 或者直接配置ObjectMapper bean @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return objectMapper; } }常见的全局配置包括:
- 日期格式化
- 忽略未知属性
- 字段命名策略
- 美化输出(
enable(SerializationFeature.INDENT_OUTPUT))
-
在
application.yml或application.properties中配置 Spring Boot允许在配置文件中设置一些Jackson的全局属性:application.yml示例:
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss # 日期格式 time-zone: GMT+8 # 时区 property-naming-strategy: SNAKE_CASE # 属性命名策略,如下划线 default-property-inclusion: NON_NULL # 默认忽略null值属性 serialization: write-dates-as-timestamps: false # 不将日期写为时间戳application.properties示例:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.property-naming-strategy=SNAKE_CASE spring.jackson.default-property-inclusion=NON_NULL spring.jackson.serialization.write-dates-as-timestamps=false
替换Jackson(如使用Gson或Fastjson)
虽然Jackson是Spring Boot的默认选择,但你也可以替换为其他JSON库,如Google Gson或阿里巴巴的Fastjson。
-
替换为Gson
-
移除Jackson依赖(如果存在)。
-
添加Gson依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> -
配置
GsonHttpMessageConverter:import com.google.gson.Gson; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.context.annotation.Bean; import org.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.GsonHttpMessageConverter; @Configuration public class GsonConfig { @Bean public HttpMessageConverters customConverters() { GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter(); gsonHttpMessageConverter.setGson(new Gson()); // 可以自定义Gson实例 return new HttpMessageConverters(gsonHttpMessageConverter); } }
-
-
替换为Fastjson
-
添加Fastjson依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> <!-- 使用合适的版本 --> </dependency> -
配置
FastJsonHttpMessageConverter:import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.context.annotation.Bean; import org.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import java.nio.charset.StandardCharsets; import java.util.ArrayList;
-



还没有评论,来说两句吧...