作者:闷气敦厚 | 来源:互联网 | 2023-10-17 11:21
LoginController页面如下:
public Object login(@RequestBody User user) {
return xxxx;
}
User 类属性:
private LocalDateTime birthDay; //出生日期
postman测试:
传入日期 "birthDay": "2014-01-01T01:00:00", 后台可以接收
传入"birthDay": "2014-01-01 01:00:00", 页面有如下异常信息:
"message": "JSON parse error: Can not deserialize value of type java.time.LocalDateTime from String \"2018-11-09 12:36:28.242\": Text '2018-11-09 12:36:28.242' could not be parsed at index 10;
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDateTime from String \"2018-11-09 12:36:28.242\":
Text '2018-11-09 12:36:28.242' could not be parsed at index 10\n at [Source: java.io.PushbackInputStream@9ea12ad;
自己确实花了点时间。终于解决:
本文中用的序列化方式为:
Maven: com.fasterxml.jackson.core:jackson-databind:2.8.8
@Bean
public ObjectMapper objectMapper() {
bjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new GuavaModule());
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
1.为什么传2014-01-01T01:00:00 这个字符串可以被后台解析呢?
原因在JavaTimeModule类中:
默认配置对LocalDateTime配置序列化和反序列化类
LocalDateTimeSerializer类默认日期格式,有个 T 拼接字符,问题就出在这里,所以2014-01-01 01:00:00后台反序列化失败
解决代码:自己指定日期解析格式
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());
JavaTimeModule module = new JavaTimeModule();
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(module);