SpringBoot中使用Jackson 统一配置日期格式

本文介绍Spring Boot如何配置Jackson统一转换日期格式。此前文章已提及Jackson的优秀转换能力,这里介绍两种配置方式,一是在配置文件yml中配置,二是在配置类中创建JacksonConfig.java文件进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#概述
在《Jackson,强大的java json解析器,方便json字符串、对象bean、map、数组list互相转换》一文中已经介绍了jackson的各种优秀转换能力,
这里继续介绍SpringBoot如何配置jackson,来统一转换日期格式

Jackson 统一配置 日期转换格式

方式一:配置文件yml中配置

spring:
    jackson:
        default-property-inclusion: ALWAYS
        time-zone: GMT+8
        date-format: yyyy-MM-dd HH:mm:ss

这样序列化后,Date类型会被格式化成配置中的格式。

方式二:配置类中配置
创建JacksonConfig.java

@Configuration
public class JacksonConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder builder) {
                builder.serializerByType(LocalDateTime.class,
                        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.serializerByType(LocalDate.class,
                        new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.serializerByType(LocalTime.class,
                        new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.deserializerByType(LocalDateTime.class,
                        new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.deserializerByType(LocalDate.class,
                        new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.deserializerByType(LocalTime.class,
                        new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.serializationInclusion(JsonInclude.Include.NON_NULL);
                builder.failOnUnknownProperties(false);
                builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            }
        };
    }
}

总结

以上就是常用的Jackson 统一配置日期格式。

### 如何在 Spring Boot 中进行日期格式的转换 在 Spring Boot 中,可以通过自定义消息转换器或者使用注解的方式来进行日期格式的转换。以下是两种常见的实现方式: #### 方法一:通过 `@JsonFormat` 注解实现日期格式Spring Boot 集成了 Jackson 库,默认支持 JSON 数据的序列化和反序列化操作。对于日期类型的字段,可以直接使用 `@JsonFormat` 注解指定日期格式。 ```java import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class User { private String name; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") // 设置日期格式并指定时区 private Date birthDate; // Getter 和 Setter 方法 } ``` 上述代码中,`pattern` 属性指定了日期的时间格式为 `"yyyy-MM-dd HH:mm:ss"`,而 `timezone` 属性则设置了目标时区为 GMT+8[^1]。 --- #### 方法二:通过全局配置文件设置默认日期格式 如果希望在整个项目中统一管理日期格式,可以在 `application.properties` 或者 `application.yml` 文件中进行全局配置。 ##### 使用 `application.properties` ```properties spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 ``` ##### 使用 `application.yml` ```yaml spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 ``` 以上配置会使得所有的日期对象都按照指定的格式进行序列化和反序列化[^2]。 --- #### 方法三:自定义消息转换器处理复杂的日期格式需求 当项目的日期格式较为复杂或存在多种不同的格式时,可以创建一个自定义的消息转换器来满足特定的需求。 ##### 步骤说明: 1. 创建一个新的类继承 `HttpMessageConverter` 接口。 2. 实现其核心方法(如 `canRead`, `canWrite`, `readInternal`, `writeInternal`)。 3. 将该转换器注册到 Spring Boot 的消息转换器列表中。 以下是一个简单的示例代码片段: ```java import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.text.SimpleDateFormat; import java.util.List; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { CustomDateConverter customDateConverter = new CustomDateConverter(); converters.add(customDateConverter); } } class CustomDateConverter extends AbstractHttpMessageConverter<Date> { private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); protected boolean supports(Class<?> clazz) { return Date.class.equals(clazz); } @Override protected Date readInternal(Class<? extends Date> clazz, HttpInputMessage inputMessage) throws IOException { String dateString = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset()); try { return dateFormat.parse(dateString); } catch (ParseException e) { throw new RuntimeException(e); } } @Override protected void writeInternal(Date t, HttpOutputMessage outputMessage) throws IOException { outputMessage.getBody().write(dateFormat.format(t).getBytes()); } } ``` 此代码展示了如何编写一个自定义的消息转换器,并将其集成到 Spring Boot 的 MVC 架构中。 --- ### 总结 - 如果仅需简单地调整日期格式,推荐使用 `@JsonFormat` 注解或修改全局配置文件。 - 对于更高级的应用场景,则可通过扩展 `HttpMessageConverter` 来构建定制化的解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值