Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTimeFormatter with ObjectMapper

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

like image 645
DanglingPointer Avatar asked Oct 10 '16 09:10

DanglingPointer


People also ask

Can ObjectMapper be reused?

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.

Is ObjectMapper thread safe?

Mapper instances are fully thread-safe provided that ALL configuration of the instance occurs before ANY read or write calls.

How do I change the date format in ObjectMapper?

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.


1 Answers

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>
like image 188
cassiomolin Avatar answered Oct 19 '22 08:10

cassiomolin