作者:用户19910071 | 来源:互联网 | 2023-02-06 21:25
我有以下配置:
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
return objectMapper;
}
以及依赖关系:
ext {
springBootVersion = '1.5.2.RELEASE'
}
....
dependencies {
compile('org.springframework.boot:spring-boot-starter-websocket')
compile("org.springframework:spring-messaging")
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-validation')
compile('org.springframework.boot:spring-boot-starter-web')
compile group: 'net.jcip', name: 'jcip-annotations', version: '1.0'
compile ("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
我添加了以下控制器:
@PostMapping("/validation_test")
public String testValidation(@Valid @RequestBody ClientInputMessage clientInputMessage, BindingResult result) {
logger.info(Arrays.toString(result.getAllErrors().toArray()));
return "main";
}
public class ClientInputMessage {
@NotEmpty
private String num1;
@NotEmpty
private String num2;
@Past
private LocalDateTime date;
如果我像这样传递json:
{
"num1":"324",
"num2":123,
"date":"2014-01-01"
}
应用程序打印输出:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize value of type java.time.LocalDateTime from String "2014-01-01": Text '2014-01-01' could not be parsed at index 10
at [Source: java.io.PushbackInputStream@1204f40f; line: 4, column: 8] (through reference chain: model.ClientInputMessage["date"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.time.LocalDateTime from String "2014-01-01": Text '2014-01-01' could not be parsed at index 10
at [Source: java.io.PushbackInputStream@1204f40f; line: 4, column: 8] (through reference chain: model.ClientInputMessage["date"])
小智..
7
原始答案:
java中的LocalDateTime不接受"2014-01-01"作为有效日期字符串.
一些额外的信息:
如果你实际上并不关心你的日期是什么类型(LocalDate,OffsetDate,ZonedDate,...),你可以使它成为TemporalAccessor,然后使用DateTimeFormatter :: parseBest来解析日期.
PS
字符串"2014-01-01T00:00:00"对LocalDateTime有效
1> 小智..:
原始答案:
java中的LocalDateTime不接受"2014-01-01"作为有效日期字符串.
一些额外的信息:
如果你实际上并不关心你的日期是什么类型(LocalDate,OffsetDate,ZonedDate,...),你可以使它成为TemporalAccessor,然后使用DateTimeFormatter :: parseBest来解析日期.
PS
字符串"2014-01-01T00:00:00"对LocalDateTime有效
仅供参考:java.time的类文档通常建议避免使用更通用的接口,例如`TemporalAccessor`.此类接口仅供*在框架内使用*.引用:*此接口是一个框架级接口,不应在应用程序代码中广泛使用.相反,应用程序应该创建并传递具体类型的实例......*