Jackson will convert java.util.Date and java.util.Time nicely and the output will be in yyyy-MM-dd, HH: MM: ss and other formats. On the other hand, the Local ~ class of the java.time package added after Java 8 does not serialize well, and it is processed as an associative array as follows.
(The following source code is inconsistent because it uses the execution time to get the date and time.)
{"id":1,"name":"hoge","registrationDateTime":{"dayOfMonth":19,"dayOfWeek":"WEDNESDAY","dayOfYear":262,"month":"SEPTEMBER","monthValue":9,"year":2018,"hour":10,"minute":28,"nano":916000000,"second":37,"chronology":{"id":"ISO","calendarType":"iso8601"}}}
With this, there is a lot of unnecessary information, and the recipient will be in trouble, so I would like to do the following.
{"id":1,"name":"hoge","registrationDateTime":"2018/09/19 10:29:30"}
First, you need to explicitly register the following modules in the ObjectMapper instance so that Jackson can handle java.time.
By using this class as follows, java.time will be serialized to some extent in an easy-to-understand manner.
ObjectMapper om = new ObjectMapper();
JavaTimeModule jtm = new JavaTimeModule();
om.registerModule(jtm);
As a result, it will be serialized as follows.
{"id":1,"name":"hoge","registrationDateTime":[2018,9,19,10,24,49,73000000]}
This is still awkward, so we need to change the default format.
Any format can be specified as follows.
jtm.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
As a result, it will be serialized as follows.
{"id":1,"name":"hoge","registrationDateTime":"2018/09/19 10:29:30"}
This time I'm focusing on serialization, but when deserializing the date and time to JavaObject using java.time, an exception will occur if the format is yyyy / MM / dd, so it is the same as the procedure for registering Serializer. You also need to register the Desirializer in as follows.
jtm.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
The source code used for the explanation is listed in git. Please try it.
Recommended Posts