Files
jackson3-by-example/src/main/java/com/ankurm/jackson3/beyond/Y03DateTimeDefaults.java
T
asmhatre c438afc33b Jackson 3 series companion code
37 runnable examples covering the eight feature posts on ankurm.com, verified
against Jackson 3.2.1 on Temurin 21.0.5. Every output committed under docs/ was
produced by run-all.sh.

Also documents 11 places where the published snippets do not compile or do not
behave as printed against a real Jackson 3 build - most notably that
writeValueAsString(List<Base>) silently drops the polymorphic type discriminator,
so the post's serialised output cannot be read back.
2026-08-04 23:29:26 +05:30

63 lines
2.6 KiB
Java

package com.ankurm.jackson3.beyond;
import tools.jackson.databind.cfg.DateTimeFeature;
import tools.jackson.databind.json.JsonMapper;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
/**
* BEYOND THE POSTS — where WRITE_DATES_AS_TIMESTAMPS actually lives.
*
* Several of the blog snippets carry `.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)`
* over from Jackson 2. That constant does NOT exist on SerializationFeature in Jackson 3;
* the code does not compile. The flag moved to tools.jackson.databind.cfg.DateTimeFeature
* and, more usefully, it now defaults to OFF — so ISO-8601 output needs no configuration
* at all and there is nothing to disable.
*/
public class Y03DateTimeDefaults {
public record Meeting(LocalDate day, LocalDateTime startsAt,
Instant recordedAt, ZonedDateTime zoned, Duration length) { }
public static void main(String[] args) {
System.out.println("SerializationFeature has WRITE_DATES_AS_TIMESTAMPS : "
+ hasSerializationFeature("WRITE_DATES_AS_TIMESTAMPS"));
System.out.println("DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS default : "
+ JsonMapper.builder().build().serializationConfig()
.isEnabled(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS));
System.out.println();
Meeting meeting = new Meeting(
LocalDate.of(2026, 9, 15),
LocalDateTime.of(2026, 9, 15, 10, 30),
Instant.parse("2026-09-15T10:30:00Z"),
ZonedDateTime.parse("2026-09-15T10:30:00Z"),
Duration.ofMinutes(45));
JsonMapper defaults = JsonMapper.builder().build();
System.out.println("defaults (ISO-8601):");
System.out.println(" " + defaults.writeValueAsString(meeting));
JsonMapper timestamps = JsonMapper.builder()
.enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
System.out.println("with WRITE_DATES_AS_TIMESTAMPS enabled:");
System.out.println(" " + timestamps.writeValueAsString(meeting));
// Both forms read back, so an upgrade does not break existing stored payloads.
String numeric = timestamps.writeValueAsString(meeting);
System.out.println("numeric form reads back: " + defaults.readValue(numeric, Meeting.class).day());
}
private static boolean hasSerializationFeature(String name) {
for (var f : tools.jackson.databind.SerializationFeature.values()) {
if (f.name().equals(name)) return true;
}
return false;
}
}