目录
1,非Spring boot环境下,直接使用ObjectMapper序列化LocaleDateTime会报错
2,ObjectMapper使用findAndRegisterModules(),序列化正常,序列化后日期格式为非常用格式
3,Mapper设置DateFormat后,日期格式改变为ISO模式,与设置的Pattern不匹配
4,使用JavaTimeModule设置LocaleDateTime序列器并将其注册到ObjectMapper中,序列化后日期格式满足设定值
1,非Spring boot环境下,直接使用ObjectMapper序列化LocaleDateTime会报错
在非Spring boot情况下,没有使用自动配置,使用ObjectMapper序列化LocaleDateTime对象时会报错
public void systemMillisTest() throws Exception {
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(1676104662050L), ZoneId.systemDefault());
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("过期时间:" + objectMapper.writeValueAsString(time));
}
运行后报错,提示需要添加jackson-datatype-jsr310,实际上项目资源有导入这个包
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
2,ObjectMapper使用findAndRegisterModules(),序列化正常,序列化后日期格式为非常用格式
public void systemMillisTest() throws Exception {
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(1676104662050L), ZoneId.systemDefault());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
System.out.println("过期时间:" + objectMapper.writeValueAsString(time));
}
过期时间:[2023,2,11,16,37,42,50000000]
Process finished with exit code 0
3,Mapper设置DateFormat后,日期格式改变为ISO模式,与设置的Pattern不匹配
public void systemMillisTest() throws Exception {
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(1676104662050L), ZoneId.systemDefault());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(dateFormat);
System.out.println("过期时间:" + objectMapper.writeValueAsString(time));
}
过期时间:"2023-02-11T16:37:42.05"
Process finished with exit code 0
4,使用JavaTimeModule设置LocaleDateTime序列器并将其注册到ObjectMapper中,序列化后日期格式满足设定值
public void systemMillisTest() throws Exception {
LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(1676104662050L), ZoneId.systemDefault());
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addDeserializer(LocalDateTime.class, new
LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
timeModule.addSerializer(LocalDateTime.class, new
LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(timeModule);
System.out.println("过期时间:" + objectMapper.writeValueAsString(time));
}
过期时间:"2023-02-11 16:37:42"
Process finished with exit code 0