Java 8 中 Jackson 序列化 LocalDateTime 的问题解决

项目场景:

项目场景:系统之间Post请求,把对象序列化成json字符串作为参数传递

问题描述:

实体类中有LocalDateTime属性字段,对其转换为Json字符串时,格式出错。


解决方案:

1、实体类

@Data
public class User {
    
    

    private String name;
    
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime liveStartTime;
}

2、测试代码

    public static void main(String[] args) throws Exception {
    
    
        ScheduleListVoV2 scheduleListVoV2 = new ScheduleListVoV2();
        scheduleListVoV2.setScheduleName("测试");
        scheduleListVoV2.setLiveStartTime(LocalDateTime.now());
        ObjectMapper mapper = new ObjectMapper();
        String requestBody = mapper.writeValueAsString(scheduleListVoV2);
        System.out.println(requestBody);
    }

3、输出结果

{
    
    "scheduleName":"测试""liveStartTime":{"nano":780000000,"dayOfMonth":10,"dayOfWeek":"FRIDAY","dayOfYear":344,"hour":16,"minute":55,"month":"DECEMBER","monthValue":12,"second":54,"year":2021,"chronology":{"id":"ISO","calendarType":"iso8601"}}}

可以看到时间格式不是我们想要的yyyy-MM-dd HH:mm:ss格式

4、解决办法

  1. 增加jackson-datatype-jsr310依赖,在pom.xml中添加
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
  1. 在new出ObjectMapper对象后注册上刚才添加的依赖模块mapper.findAndRegisterModules(),如下:
    public static void main(String[] args) throws Exception {
    
    
        ScheduleListVoV2 scheduleListVoV2 = new ScheduleListVoV2();
        scheduleListVoV2.setScheduleName("测试");
        scheduleListVoV2.setLiveStartTime(LocalDateTime.now());
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules();
        String requestBody = mapper.writeValueAsString(scheduleListVoV2);
        System.out.println(requestBody);
    }

3.输出结果

{
    
    "scheduleName":"测试","liveStartTime":"2021-12-10 17:13:27"}

完美解决!序列化和反序列同时适用。

猜你喜欢

转载自blog.csdn.net/hurtseverywhere/article/details/121859917