Jackson Date

1. Ikhtisar

Dalam tutorial ini, kami akan membuat serial tanggal dengan Jackson. Kami akan mulai dengan membuat serial java.util sederhana. Date , lalu Joda-Time serta Java 8 DateTime .

2. Atur Tanggal ke Stempel Waktu

Pertama - mari kita lihat bagaimana membuat serial java.util.Date sederhana dengan Jackson .

Dalam contoh berikut - kami akan membuat serial instance " Event " yang memiliki bidang Tanggal " eventDate ":

@Test public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = df.parse("01-01-1970 01:00"); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); mapper.writeValueAsString(event); }

Yang penting di sini adalah Jackson akan membuat serial Tanggal ke format stempel waktu secara default (jumlah milidetik sejak 1 Januari 1970, UTC).

Keluaran sebenarnya dari serialisasi " acara " adalah:

{ "name":"party", "eventDate":3600000 }

3. Tanggal Serial ke ISO-8601

Serialisasi ke format stempel waktu singkat ini tidak optimal. Sekarang mari kita membuat serial Tanggal ke format ISO-8601 :

@Test public void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String toParse = "01-01-1970 02:30"; Date date = df.parse(toParse); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // StdDateFormat is ISO8601 since jackson 2.9 mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); String result = mapper.writeValueAsString(event); assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); }

Perhatikan bagaimana representasi tanggal sekarang jauh lebih mudah dibaca.

4. Konfigurasi DateFormat ObjectMapper

Solusi sebelumnya masih kurang memiliki fleksibilitas penuh dalam memilih format yang tepat untuk merepresentasikan instance java.util.Date .

Sekarang mari kita lihat konfigurasi yang memungkinkan kita mengatur format untuk merepresentasikan tanggal :

@Test public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); String toParse = "20-12-2014 02:30"; Date date = df.parse(toParse); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); String result = mapper.writeValueAsString(event); assertThat(result, containsString(toParse)); }

Perhatikan bahwa, meskipun kami sekarang lebih fleksibel terkait format tanggal - kami masih menggunakan konfigurasi global pada level seluruh ObjectMapper .

5. Gunakan @JsonFormat untuk Memformat Tanggal

Selanjutnya, mari kita lihat anotasi @JsonFormat untuk mengontrol format tanggal pada masing-masing kelas, bukan secara global, untuk seluruh aplikasi:

public class Event { public String name; @JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") public Date eventDate; }

Sekarang - mari kita uji:

@Test public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); String toParse = "20-12-2014 02:30:00"; Date date = df.parse(toParse); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(event); assertThat(result, containsString(toParse)); }

6. Serializer Tanggal Kustom

Selanjutnya - untuk mendapatkan kontrol penuh atas output, kami akan memanfaatkan serializer khusus untuk Tanggal:

public class CustomDateSerializer extends StdSerializer { private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); public CustomDateSerializer() { this(null); } public CustomDateSerializer(Class t) { super(t); } @Override public void serialize (Date value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); } }

Selanjutnya - mari kita gunakan sebagai serializer bidang " eventDate ":

public class Event { public String name; @JsonSerialize(using = CustomDateSerializer.class) public Date eventDate; }

Akhirnya - mari kita uji:

@Test public void whenUsingCustomDateSerializer_thenCorrect() throws JsonProcessingException, ParseException { SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); String toParse = "20-12-2014 02:30:00"; Date date = df.parse(toParse); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(event); assertThat(result, containsString(toParse)); }

7. Menyusun Joda-Waktu Dengan Jackson

Tanggal tidak selalu merupakan turunan dari java.util.Date ; sebenarnya - mereka semakin banyak diwakili oleh beberapa kelas lain - dan yang umum, tentu saja, implementasi DateTime dari perpustakaan Joda-Time.

Mari kita lihat bagaimana kita dapat membuat serial DateTime dengan Jackson .

Kami akan menggunakan modul jackson-datatype-joda untuk dukungan Joda-Time out-of-the-box:

 com.fasterxml.jackson.datatype jackson-datatype-joda 2.9.7 

Dan sekarang kita cukup mendaftarkan JodaModule dan selesai:

@Test public void whenSerializingJodaTime_thenCorrect() throws JsonProcessingException { DateTime date = new DateTime(2014, 12, 20, 2, 30, DateTimeZone.forID("Europe/London")); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JodaModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String result = mapper.writeValueAsString(date); assertThat(result, containsString("2014-12-20T02:30:00.000Z")); }

8. Buat Serialisasi DateTime Joda Dengan Custom Serializer

Jika kita tidak menginginkan ketergantungan Joda-Time Jackson ekstra - kita juga dapat menggunakan serializer khusus (mirip dengan contoh sebelumnya) untuk mendapatkan instance DateTime yang diserialkan dengan rapi:

public class CustomDateTimeSerializer extends StdSerializer { private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); public CustomDateTimeSerializer() { this(null); } public CustomDateTimeSerializer(Class t) { super(t); } @Override public void serialize (DateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.print(value)); } }

Berikutnya - mari kita gunakan sebagai serializer " eventDate " properti kita :

public class Event { public String name; @JsonSerialize(using = CustomDateTimeSerializer.class) public DateTime eventDate; }

Akhirnya - mari kita gabungkan semuanya dan mengujinya:

@Test public void whenSerializingJodaTimeWithJackson_thenCorrect() throws JsonProcessingException { DateTime date = new DateTime(2014, 12, 20, 2, 30); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(event); assertThat(result, containsString("2014-12-20 02:30")); }

9. Serialize Java 8 Date With Jackson

Selanjutnya - mari kita lihat cara membuat serial Java 8 DateTime - dalam contoh ini, LocalDateTime - menggunakan Jackson . Kita dapat menggunakan modul jackson-datatype-jsr310 :

 com.fasterxml.jackson.datatype jackson-datatype-jsr310 2.9.7 

Sekarang, yang perlu kita lakukan hanyalah mendaftarkan JavaTimeModule ( JSR310Module tidak digunakan lagi) dan Jackson akan mengurus sisanya:

@Test public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException { LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); String result = mapper.writeValueAsString(date); assertThat(result, containsString("2014-12-20T02:30")); }

10. Serialize Java 8 Date Tanpa Ketergantungan Ekstra

Jika Anda tidak menginginkan ketergantungan tambahan, Anda selalu dapat menggunakan serializer khusus untuk menulis Java 8 DateTime ke JSON :

public class CustomLocalDateTimeSerializer extends StdSerializer { private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); public CustomLocalDateTimeSerializer() { this(null); } public CustomLocalDateTimeSerializer(Class t) { super(t); } @Override public void serialize( LocalDateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException { gen.writeString(formatter.format(value)); } }

Berikutnya - mari gunakan serializer untuk bidang " eventDate ":

public class Event { public String name; @JsonSerialize(using = CustomLocalDateTimeSerializer.class) public LocalDateTime eventDate; }

Sekarang - mari kita uji:

@Test public void whenSerializingJava8DateWithCustomSerializer_thenCorrect() throws JsonProcessingException { LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); Event event = new Event("party", date); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(event); assertThat(result, containsString("2014-12-20 02:30")); }

11. Deserialize Tanggal

Selanjutnya - mari kita lihat cara menghilangkan nama Kencan dengan Jackson . Dalam contoh berikut - kami deserialize sebuah instance " Event " yang berisi tanggal:

@Test public void whenDeserializingDateWithJackson_thenCorrect() throws JsonProcessingException, IOException { String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}"; SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(df); Event event = mapper.readerFor(Event.class).readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); }

12. Deserialize Joda ZonedDateTime With Time Zone Preserved

In its default configuration, Jackson adjusts the time zone of a Joda ZonedDateTime to the time zone of the local context. As, by default, the time zone of the local context is not set and has to be configured manually, Jackson adjusts the time zone to GMT:

@Test public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); String converted = objectMapper.writeValueAsString(now); ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); System.out.println("serialized: " + now); System.out.println("restored: " + restored); assertThat(now, is(restored)); }

This test case will fail with output:

serialized: 2017-08-14T13:52:22.071+02:00[Europe/Berlin] restored: 2017-08-14T11:52:22.071Z[UTC]

Fortunately, there is a quick and simple fix for this odd default-behavior: we just have to tell Jackson, not to adjust the time zone.

This can be done by adding the below line of code to the above test case:

objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

Note that, to preserve time zone we also have to disable the default behavior of serializing the date to the timestamp.

13. Custom Date Deserializer

Let's also see how to use a custom Date deserializer; we'll write a custom deserializer for the property “eventDate“:

public class CustomDateDeserializer extends StdDeserializer { private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); public CustomDateDeserializer() { this(null); } public CustomDateDeserializer(Class vc) { super(vc); } @Override public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JsonProcessingException { String date = jsonparser.getText(); try { return formatter.parse(date); } catch (ParseException e) { throw new RuntimeException(e); } } }

Next – let's use it as the “eventDate” deserializer:

public class Event { public String name; @JsonDeserialize(using = CustomDateDeserializer.class) public Date eventDate; }

And finally – let's test it:

@Test public void whenDeserializingDateUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException { String json = "{"name":"party","eventDate":"20-12-2014 02:30:00"}"; SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); ObjectMapper mapper = new ObjectMapper(); Event event = mapper.readerFor(Event.class).readValue(json); assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); }

14. Fixing InvalidDefinitionException

When creating a LocalDate instance, we may come across an exception:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate`(no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2014-12-20') at [Source: (String)"2014-12-20"; line: 1, column: 1]

This problem occurs because JSON doesn't natively have a date format, so represents dates as String.

The String representation of a date isn't the same as an object of type LocalDate in memory, so we need an external deserializer to read that field from a String, and a serializer to render the date to String format.

These methods also apply to LocalDateTime — the only change is to use an equivalent class for LocalDateTime.

14.1. Jackson Dependency

Jackson allows us to fix this a couple of ways. First, we have to make sure the jsr310 dependency is in our pom.xml:

 com.fasterxml.jackson.datatype jackson-datatype-jsr310 2.11.0 

14.2. Serialization to Single Date Object

In order to be able to handle LocalDate, we need to register the JavaTimeModule with our ObjectMapper.

We also disable the feature WRITE_DATES_AS_TIMESTAMPS in ObjectMapper to prevent Jackson from adding time digits to the JSON output:

@Test public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException { String stringDate = "\"2014-12-20\""; ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); LocalDate result = mapper.readValue(stringDate, LocalDate.class); assertThat(result.toString(), containsString("2014-12-20")); }

Here, we've used Jackson's native support for serializing and deserializing dates.

14.3. Annotation in POJO

Another way to deal with that problem is to use the LocalDateDeserializer and JsonFormat annotations at the entity level:

public class EventWithLocalDate { @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") public LocalDate eventDate; }

The @JsonDeserialize annotation is used to specify a custom deserializer to unmarshal the JSON object. Similarly, @JsonSerialize indicates a custom serializer to use when marshaling the entity.

In addition, the annotation @JsonFormat allows us to specify the format to which we will serialize date values. Therefore, this POJO can be used to read and write the JSON:

@Test public void whenSerializingJava8DateAndReadingFromEntity_thenCorrect() throws IOException { String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014\"}"; ObjectMapper mapper = new ObjectMapper(); EventWithLocalDate result = mapper.readValue(json, EventWithLocalDate.class); assertThat(result.getEventDate().toString(), containsString("2014-12-20")); }

While this approach takes more work than using the JavaTimeModule defaults, it's a lot more customizable.

15. Conclusion

In this extensive Date article, we looked at several ways Jackson can help marshal and unmarshal a date to JSON using a sensible format we have control over.

Seperti biasa, kode contoh dapat ditemukan di GitHub.