Tarikh Jackson

1. Gambaran keseluruhan

Dalam tutorial ini, kami akan membuat siri tarikh dengan Jackson. Kita akan mulakan dengan menyusun java.util ringkas. Tarikh , kemudian Joda-Time dan juga Java 8 DateTime .

2. Bersiri Tarikh ke Cap Waktu

Pertama - mari kita lihat cara membuat siri java.util sederhana dengan Jackson .

Dalam contoh berikut - kami akan membuat siri kejadian " Event " yang mempunyai bidang Date " 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 ialah Jackson akan memaparkan format Tarikh ke cap waktu secara lalai (bilangan milisaat sejak 1 Januari 1970, UTC).

Output sebenar dari " peristiwa " bersiri adalah:

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

3. Tarikh Bersiri ke ISO-8601

Serial ke format cap waktu yang singkat ini tidak optimum. Mari sekarang bersiri format Tarikh ke 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 perwakilan tarikh sekarang lebih mudah dibaca.

4. Konfigurasikan ObjectMapper DateFormat

Penyelesaian sebelumnya masih kurang fleksibiliti untuk memilih format yang tepat untuk mewakili contoh java.util.Date .

Sekarang mari kita lihat konfigurasi yang membolehkan kita menetapkan format untuk mewakili tarikh :

@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 bahawa, walaupun kita sekarang lebih fleksibel mengenai format tanggal - kita masih menggunakan konfigurasi global pada tingkat keseluruhan ObjectMapper .

5. Gunakan @JsonFormat untuk Memformat Tarikh

Seterusnya, mari kita lihat penjelasan @JsonFormat untuk mengawal format tarikh pada kelas individu dan bukannya secara global, untuk keseluruhan 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 mengujinya:

@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 Tarikh Tersuai

Seterusnya - untuk mendapatkan kawalan penuh terhadap output, kami akan memanfaatkan alat penyusun khas untuk Tarikh:

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)); } }

Seterusnya - mari kita gunakan sebagai serializer bidang " eventDate " kami :

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

Akhirnya - mari kita mengujinya:

@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. Serial Joda-Time Bersama Jackson

Tarikh tidak selalu menjadi contoh java.util.Date ; sebenarnya - mereka lebih banyak ditunjukkan oleh beberapa kelas lain - dan yang biasa, tentu saja, pelaksanaan DateTime dari perpustakaan Joda-Time

Mari lihat bagaimana kita boleh membuat siri DateTime dengan Jackson .

Kami akan menggunakan modul jackson-datatype-joda untuk sokongan Joda-Time di luar kotak:

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

Dan sekarang kita boleh 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. Serialize Joda DateTime Dengan Custom Serializer

Sekiranya kita tidak mahu kebergantungan tambahan Joda-Time Jackson - kita juga boleh menggunakan penyesuai tersuai (serupa dengan contoh sebelumnya) untuk mendapatkan contoh DateTime bersiri dengan bersih:

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)); } }

Seterusnya - mari kita gunakan sebagai serializer " eventDate " milik kita :

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

Akhirnya - mari kita satukan semuanya dan uji:

@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 dengan Jackson

Seterusnya - mari kita lihat cara membuat siri Java 8 DateTime - dalam contoh ini, LocalDateTime - menggunakan Jackson . Kita boleh menggunakan modul jackson-datatype-jsr310 :

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

Sekarang, yang perlu kita lakukan ialah mendaftarkan JavaTimeModule ( JSR310Module tidak digunakan lagi) dan Jackson akan menguruskan selebihnya:

@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 Tarikh Tanpa Ketergantungan Tambahan

Sekiranya anda tidak mahukan kebergantungan tambahan, anda selalu boleh menggunakan alat penyusun khas 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)); } }

Seterusnya - mari gunakan serializer untuk bidang " eventDate " kami :

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

Sekarang - mari kita mengujinya:

@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. Tarikh Deserialize

Seterusnya - mari kita lihat cara mendeserisasi Tarikh dengan Jackson . Dalam contoh berikut - kami mendesialisasikan contoh " Peristiwa " yang mengandungi tarikh:

@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 Dengan Zon Waktu Terpelihara

Dalam konfigurasi lalai, Jackson menyesuaikan zon waktu Joda ZonedDateTime ke zon waktu konteks tempatan. Oleh kerana, secara lalai, zon waktu konteks tempatan tidak ditetapkan dan harus dikonfigurasi secara manual, Jackson menyesuaikan zon waktu ke 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)); }

Kes ujian ini akan gagal dengan output:

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

Nasib baik, ada penyelesaian cepat dan sederhana untuk tingkah laku lalai yang ganjil ini: kita hanya perlu memberitahu Jackson, untuk tidak menyesuaikan zon waktu.

Ini boleh dilakukan dengan menambahkan baris kod di bawah pada kes ujian di atas:

objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

Perhatikan bahawa, untuk mengekalkan zon waktu, kita juga harus melumpuhkan tingkah laku lalai untuk menyusun tarikh ke cap waktu.

13. Deserializer Tarikh Tersuai

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, kod contoh boleh didapati di GitHub.