2017-04-11 39 views
2
反序列化類型java.time.LocalDateTime的值

我具有以下配置:無法從字符串

@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: [email protected]; 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: [email protected]; line: 4, column: 8] (through reference chain: model.ClientInputMessage["date"]) 
+4

嘗試「date」:「2014-01-01T00:00:00」。 Java中的LocalDateTime不接受「2014-01-01」作爲有效的日期字符串。 –

+1

@Jure Kolenko OOPS,它的工作原理 – gstackoverflow

+1

對於諸如「2014-01-01」之類的僅包含日期的值,使用LocalDate類而不是LocalDateTime類。此外,如果您的問題得到解決,那麼您或Kolenko應該發佈答案以接受關閉此問題。 –

回答

4

原來的答覆:

LocalDateTime在java中不接受 「2014年1月1日」 作爲一個有效的日期字符串。

一些額外的信息:

如果你不真正關心什麼類型的日期是(LOCALDATE的,OffsetDate,ZonedDate,...),你可以把它TemporalAccessor,然後用DateTimeFormatter::parseBest解析日期。

P.S.
字符串「2014-01-01T00:00:00」對LocalDateTime有效

+3

供參考:類的文檔爲java.time提供建議,通常是爲了避免使用更常用的接口,例如'TemporalAccessor'。這些接口僅用於*框架內。引用:*此接口是一個框架級接口,不應在應用程序代碼中廣泛使用。相反,應用程序應創建並傳遞具體類型的實例... * –