Prior to Java8, we used to set DateFormat with ObjectMapper as follows
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
ObjectMapper mapper = <SomeInstantiation>
mapper.setDateFormat(df);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Now that we have java.time.format.DateTimeFormatter which is threadsafe and more robust unlike SimpleDateFormat. I want to replace above settings on ObjectMapper.
How do I set DateTimeFormatter with ObjectMapper
ObjectMapper class can be reused and we can initialize it once as Singleton object. There are so many overloaded versions of readValue() and writeValue() methods to work with byte array, File, input/output stream and Reader/Writer objects.
Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.
We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.
You can try the following:
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);
The jackson-datatype-jsr310
dependency is required:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.2</version>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With