SpringBoot 使用 jackson 格式化时间

简介: 在实际开发中我们经常会与时间打交道,那这就会涉及到一个时间格式转换的问题。接下来会介绍几种在SpirngBoot中如何对时间格式进行转换。
日积月累,水滴石穿 😄

在实际开发中我们经常会与时间打交道,那这就会涉及到一个时间格式转换的问题。接下来会介绍几种在SpirngBoot中如何对时间格式进行转换。

准备工作

创建项目,添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建实体类UserDTO

添加属性,get、set方法省略。

private String id;
private String username;
private Date createTime;

创建UserController

编写控制层代码

@RestController
public class UserController {
    @GetMapping("/getUser")
    public List<UserDTO> getUser() {
        List<UserDTO> userList = new ArrayList<UserDTO>();
        for (int i=1; i<=3; i++) {
            UserDTO user = new UserDTO();
            user.setCreateTime(new Date());
            user.setUsername("gongj" + i);
            user.setId("j" + i);
            userList.add(user);
        }
        return userList;
    }
    
}

调用接口:http://localhost:8080/getUser

image-20210602224447315.png

该结果很显然不是我们所需要的,所以我们需要进行时间格式化一下。而且还有时区问题,我当前时间是晚上 22:44

第一种 使用注解

在需要转换的字段上增加 @JsonFormat注解,该注解是 jackson的,web 包集成了。

import com.fasterxml.jackson.annotation.JsonFormat;

private String id;
private String username;
 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date createTime;
  • pattern:需要转换的时间日期的格式
  • timezone:时间设置为东八区,避免时间在转换中有误差

调用接口:http://localhost:8080/getUser

image-20210602225019891.png
完成,但是这种也有不好的地方,如果我有一百个实体中都有 Date类型,那就要在一百个实体加入注解。显得有点麻烦。

第二种 修改默认配置

所有的json生成都离不开相关的HttpMessageConverters
SpringBoot 默认使用 jackson,并对其默认做了配置。所以我们来修改一下。

全局搜索 JacksonHttpMessageConvertersConfiguration。idea快捷键:Ctrl + shift + r

image-20210602225301478.png

该类中有个方法mappingJackson2HttpMessageConverter 就是用来处理json的。

@Bean
@ConditionalOnMissingBean(
    value = {MappingJackson2HttpMessageConverter.class},
    ignoredType = {"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter"}
)
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
    return new MappingJackson2HttpMessageConverter(objectMapper);
}

注意该方法上有两个注解,@Bean 注解就不在介绍了。介绍一下 ConditionalOnMissingBean注解。

@ConditionalOnMissingBean :当给定的在bean不存在时,则实例化当前 Bean

打个比喻:你入职报到,你公司看你带了电脑,就让你使用你自己的电脑,如果你没带电脑,就让你使用公司的电脑。SpringBoot 也是这样子做的,你不提供,就使用默认的。

新建MyConfig

import java.text.SimpleDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class MyConfig {

    @Bean
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverterConfiguration() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper om = new ObjectMapper();
        //全局修改josn时间格式
        om.setDateFormat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        converter.setObjectMapper(om);
        return converter;
    }
}

提供了一个 MappingJackson2HttpMessageConverterBean ,所以Springboot就会使用我们所提供的。

将User实体的注解注释

image-20210602230527178.png

调用接口:http://localhost:8080/getUser

image-20210602230903840.png
OK,这种方式也是可以的。

提供ObjectMapper

也可以提供一个 ObjectMapper,将上述提供的 MappingJackson2HttpMessageConverter进行注释掉。

import java.text.SimpleDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
@Bean
ObjectMapper objectMapper() {
    ObjectMapper om = new ObjectMapper();
    om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    return om;
}

调用接口:http://localhost:8080/getUser
image-20210602231142685.png

注意:上述两种方法都是全局修改的哦!

第三种 配置文件修改

application.yml或者properties中修改默认配置

yml

spring: 
  jackson: 
    date-format: yyyy/MM/dd
    timezone: GMT+8

properties

spring.jackson.date-format=yyyy-MM-dd HH:mm
spring.jackson.time-zone=GMT+8
  • 如果第二种方式和第三种方式配置同时存在,以第二种方式为主。
  • 如果三种方式都存在的时候,以实体类中注解格式为主。
  • 如你对本文有疑问或本文有错误之处,欢迎评论留言指出。如觉得本文对你有所帮助,欢迎点赞和关注。
相关文章
|
JSON 前端开发 Java
SpringBoot中Date格式化处理
日期格式化处理:从混乱到清晰,轻松转换日期格式
739 1
|
JSON 安全 JavaScript
SpringBoot时间格式化
SpringBoot时间格式化
210 0
|
设计模式 JSON 前端开发
SpringBoot中对LocalDateTime进行格式化并解析
SpringBoot中对LocalDateTime进行格式化并解析
1528 0
|
8月前
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,日期时间格式化是前后端交互的常见痛点。本文详细解析了 **@DateTimeFormat** 和 **@JsonFormat** 两个注解的用法,分别用于将前端传入的字符串解析为 Java 时间对象,以及将时间对象序列化为指定格式返回给前端。通过完整示例代码,展示了从数据接收、业务处理到结果返回的全流程,并总结了解决时区问题和全局配置的最佳实践,助你高效处理日期时间需求。
986 0
|
8月前
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,处理前后端日期交互是一个常见问题。本文通过 **@DateTimeFormat** 和 **@JsonFormat** 两个注解,详细讲解了如何解析前端传来的日期字符串以及以指定格式返回日期数据。文章从实际案例出发,结合代码演示两者的使用场景与注意事项,解决解析失败、时区偏差等问题,并提供全局配置与局部注解的实践经验。帮助开发者高效应对日期时间格式化需求,提升开发效率。
2137 2
|
JSON Java 开发工具
jackson学习之九:springboot整合(配置文件)
熟悉和实践在springboot应用中通过application.yml对jackson进行全局设置
282 4
jackson学习之九:springboot整合(配置文件)
|
JSON fastjson Java
Spring Boot Jackson 和Fast JSON 用哪个好啊 ?
【4月更文挑战第22天】
2938 1
springboot解决jackson序列化Long类型精度失效问题
springboot解决jackson序列化Long类型精度失效问题
404 0
|
JSON 前端开发 Java
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
【SpringBoot实战专题】「开发实战系列」全方位攻克你的技术盲区之Spring定义Jackson转换Null的方法和实现案例
340 0
|
JSON 前端开发 Java
SpringBoot 日期&时间格式化处理
SpringBoot 日期&时间格式化处理
747 0