2016-10-10 134 views
0

此前Java8,我們用來與ObjectMapper設定日期格式如下使用DateTimeFormatter與ObjectMapper

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); 
ObjectMapper mapper = <SomeInstantiation> 
mapper.setDateFormat(df); 
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 

現在,我們有java.time.format.DateTimeFormatter這是線程安全的,不像SimpleDateFormat的更穩健。我想在ObjectMapper上替換上面的設置。

如何設置DateTimeFormatter與ObjectMapper

+0

從我收集的,你可以使用「配置重寫「來做類似的事情。參見[2.8 patchnote](https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.8#configuration-overrides)和[這個github問題](https://github.com/FasterXML/jackson-數據類型 - 喬達/問題/ 12)。 – Aaron

回答

0

你可以嘗試以下方法:

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; 

LocalDateTimeDeserializer dateTimeDeserializer = new LocalDateTimeDeserializer(formatter); 
LocalDateTimeSerializer dateTimeSerializer = new LocalDateTimeSerializer(formatter); 

JavaTimeModule javaTimeModule = new JavaTimeModule(); 
javaTimeModule.addDeserializer(LocalDateTime.class, dateTimeDeserializer); 
javaTimeModule.addSerializer(LocalDateTime.class, dateTimeSerializer); 

ObjectMapper mapper = new ObjectMapper(); 
mapper.registerModule(javaTimeModule); 

jackson-datatype-jsr310依賴性是必需的:

<dependency> 
    <groupId>com.fasterxml.jackson.datatype</groupId> 
    <artifactId>jackson-datatype-jsr310</artifactId> 
    <version>2.8.2</version> 
</dependency>