java-time: java.time on Jackson 3 vs 2, @JsonFormat, time zones, Spring Boot 4.2 spring.jackson.*
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/** One value of each common java.time "moment" type, with no Jackson annotations. */
|
||||
public record Meeting(LocalDate day,
|
||||
LocalDateTime wallClock,
|
||||
Instant createdAt,
|
||||
OffsetDateTime startsAt,
|
||||
ZonedDateTime reminderAt) { }
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
/** The same sample moment used by every program: 15 Dec 2026, 10:30 in India. */
|
||||
public final class Samples {
|
||||
private Samples() { }
|
||||
|
||||
public static final LocalDate DAY = LocalDate.of(2026, 12, 15);
|
||||
public static final LocalDateTime WALL = LocalDateTime.of(2026, 12, 15, 10, 30);
|
||||
public static final OffsetDateTime OFFSET = OffsetDateTime.of(WALL, ZoneOffset.ofHoursMinutes(5, 30));
|
||||
public static final ZonedDateTime ZONED = ZonedDateTime.of(WALL, ZoneId.of("Asia/Kolkata"));
|
||||
public static final Instant INSTANT = OFFSET.toInstant();
|
||||
|
||||
public static Meeting meeting() {
|
||||
return new Meeting(DAY, WALL, INSTANT, OFFSET, ZONED);
|
||||
}
|
||||
|
||||
/** Jackson wraps the useful text in the first line of a long message. */
|
||||
public static String firstLine(Throwable t) {
|
||||
return t.getClass().getSimpleName() + ": " + t.getMessage().lines().findFirst().orElse("");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Jackson 2 needs a module (and a flag) for java.time. Jackson 3 needs neither. */
|
||||
public class T01NoModuleNeeded {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Meeting meeting = Samples.meeting();
|
||||
|
||||
ObjectMapper plain2 = new ObjectMapper();
|
||||
System.out.println("== Jackson " + plain2.version() + ", plain ObjectMapper");
|
||||
try {
|
||||
plain2.writeValueAsString(meeting);
|
||||
} catch (Exception e) {
|
||||
System.out.println(Samples.firstLine(e));
|
||||
}
|
||||
|
||||
ObjectMapper module2 = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
System.out.println();
|
||||
System.out.println("== Jackson 2 + JavaTimeModule");
|
||||
System.out.println(module2.writeValueAsString(meeting));
|
||||
|
||||
JsonMapper m3 = JsonMapper.builder().build();
|
||||
System.out.println();
|
||||
System.out.println("== Jackson " + m3.version() + ", JsonMapper.builder().build()");
|
||||
String json = m3.writeValueAsString(meeting);
|
||||
System.out.println(json);
|
||||
System.out.println("registered modules : " + m3.registeredModules().size());
|
||||
System.out.println("read back : " + m3.readValue(json, Meeting.class));
|
||||
|
||||
System.out.println();
|
||||
for (String name : new String[] {
|
||||
"com.fasterxml.jackson.datatype.jsr310.JavaTimeModule",
|
||||
"tools.jackson.datatype.jsr310.JavaTimeModule",
|
||||
"tools.jackson.databind.ext.javatime.JavaTimeInitializer",
|
||||
"tools.jackson.databind.ext.javatime.ser.InstantSerializer"}) {
|
||||
boolean found;
|
||||
try {
|
||||
Class.forName(name);
|
||||
found = true;
|
||||
} catch (ClassNotFoundException e) {
|
||||
found = false;
|
||||
}
|
||||
System.out.println((found ? "present : " : "absent : ") + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.MonthDay;
|
||||
import java.time.Period;
|
||||
import java.time.Year;
|
||||
import java.time.YearMonth;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** The same values through four mappers, one block per type. */
|
||||
public class T02OutputDiff {
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper j2 = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
ObjectMapper j2iso = new ObjectMapper().registerModule(new JavaTimeModule())
|
||||
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
JsonMapper j3 = JsonMapper.builder().build();
|
||||
JsonMapper j3compat = JsonMapper.builderWithJackson2Defaults().build();
|
||||
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
values.put("LocalDate", Samples.DAY);
|
||||
values.put("LocalTime", LocalTime.of(10, 30));
|
||||
values.put("LocalDateTime", Samples.WALL);
|
||||
values.put("LocalDateTime+nanos", Samples.WALL.withNano(123_456_000));
|
||||
values.put("Instant", Samples.INSTANT);
|
||||
values.put("OffsetDateTime", Samples.OFFSET);
|
||||
values.put("ZonedDateTime", Samples.ZONED);
|
||||
values.put("Duration", Duration.ofMinutes(90));
|
||||
values.put("Period", Period.of(1, 2, 3));
|
||||
values.put("Year", Year.of(2026));
|
||||
values.put("YearMonth", YearMonth.of(2026, 12));
|
||||
values.put("MonthDay", MonthDay.of(12, 15));
|
||||
values.put("Month", Month.DECEMBER);
|
||||
values.put("DayOfWeek", DayOfWeek.TUESDAY);
|
||||
values.put("ZoneId", ZoneId.of("Asia/Kolkata"));
|
||||
values.put("ZoneOffset", ZoneOffset.ofHoursMinutes(5, 30));
|
||||
values.put("java.util.Date", Date.from(Samples.INSTANT));
|
||||
values.put("java.sql.Date", java.sql.Date.valueOf(Samples.DAY));
|
||||
values.put("Map<LocalDate,..> key", Map.of(Samples.DAY, 1));
|
||||
values.put("Map<Date,..> key", Map.of(Date.from(Samples.INSTANT), 1));
|
||||
|
||||
System.out.println("A = Jackson 2.23.0 + JavaTimeModule");
|
||||
System.out.println("B = A + disable(WRITE_DATES_AS_TIMESTAMPS)");
|
||||
System.out.println("C = Jackson 3.3.0 defaults");
|
||||
System.out.println("D = Jackson 3.3.0 builderWithJackson2Defaults()");
|
||||
for (var entry : values.entrySet()) {
|
||||
Object v = entry.getValue();
|
||||
System.out.println();
|
||||
System.out.println(entry.getKey());
|
||||
System.out.println(" A " + write(() -> j2.writeValueAsString(v)));
|
||||
System.out.println(" B " + write(() -> j2iso.writeValueAsString(v)));
|
||||
System.out.println(" C " + write(() -> j3.writeValueAsString(v)));
|
||||
System.out.println(" D " + write(() -> j3compat.writeValueAsString(v)));
|
||||
}
|
||||
}
|
||||
|
||||
interface Call { String run() throws Exception; }
|
||||
|
||||
static String write(Call call) {
|
||||
try {
|
||||
return call.run();
|
||||
} catch (Exception e) {
|
||||
return Samples.firstLine(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Prints every DateTimeFeature with its default, and what Jackson 2 compatibility mode flips. */
|
||||
public class T03FeatureDefaults {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper j3 = JsonMapper.builder().build();
|
||||
JsonMapper compat = JsonMapper.builderWithJackson2Defaults().build();
|
||||
System.out.printf("%-42s %-8s %s%n", "DateTimeFeature", "default", "with Jackson 2 defaults");
|
||||
for (DateTimeFeature f : DateTimeFeature.values()) {
|
||||
System.out.printf("%-42s %-8s %s%n", f.name(),
|
||||
j3.serializationConfig().isEnabled(f),
|
||||
compat.serializationConfig().isEnabled(f));
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("default time zone (mapper): " + j3.serializationConfig().getTimeZone().getID());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** What happens to "+05:30" when the text is read back into Java. */
|
||||
public class T04ReadingOffsets {
|
||||
static final String TEXT = "\"2026-12-15T10:30:00+05:30\"";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper j2 = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
System.out.println("input: " + TEXT);
|
||||
System.out.println();
|
||||
System.out.println("== Jackson 2.23.0 + JavaTimeModule, defaults");
|
||||
System.out.println("OffsetDateTime : " + j2.readValue(TEXT, OffsetDateTime.class));
|
||||
System.out.println("ZonedDateTime : " + j2.readValue(TEXT, ZonedDateTime.class));
|
||||
System.out.println("Instant : " + j2.readValue(TEXT, Instant.class));
|
||||
|
||||
show("Jackson 3 defaults (mapper zone UTC)", JsonMapper.builder().build());
|
||||
show("Jackson 3, defaultTimeZone(Asia/Kolkata)", JsonMapper.builder()
|
||||
.defaultTimeZone(TimeZone.getTimeZone("Asia/Kolkata")).build());
|
||||
JsonMapper keep = JsonMapper.builder()
|
||||
.disable(DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE).build();
|
||||
show("Jackson 3, ADJUST_DATES_TO_CONTEXT_TIME_ZONE disabled", keep);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== A region id survives only if you ask for it");
|
||||
JsonMapper withId = JsonMapper.builder()
|
||||
.enable(DateTimeFeature.WRITE_DATES_WITH_ZONE_ID)
|
||||
.disable(DateTimeFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
|
||||
.build();
|
||||
String plain = keep.writeValueAsString(Samples.ZONED);
|
||||
String tagged = withId.writeValueAsString(Samples.ZONED);
|
||||
System.out.println("original : " + Samples.ZONED);
|
||||
System.out.println("written by default : " + plain);
|
||||
System.out.println(" read back : " + keep.readValue(plain, ZonedDateTime.class));
|
||||
System.out.println("WRITE_DATES_WITH_ZONE_ID : " + tagged);
|
||||
System.out.println(" read back : " + withId.readValue(tagged, ZonedDateTime.class));
|
||||
}
|
||||
|
||||
static void show(String title, JsonMapper mapper) {
|
||||
System.out.println();
|
||||
System.out.println("== " + title);
|
||||
System.out.println("OffsetDateTime : " + mapper.readValue(TEXT, OffsetDateTime.class));
|
||||
System.out.println("ZonedDateTime : " + mapper.readValue(TEXT, ZonedDateTime.class));
|
||||
System.out.println("Instant : " + mapper.readValue(TEXT, Instant.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Which settings move the output: the JVM zone, the mapper zone, or neither. */
|
||||
public class T05TimeZones {
|
||||
record Values(Object localDateTime, Object instant, Object offset, Object zoned,
|
||||
Date utilDate, java.sql.Date sqlDate) { }
|
||||
|
||||
record Patterned(
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm XXX") OffsetDateTime offset,
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm XXX") ZonedDateTime zoned) { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
for (String jvmZone : new String[] {"UTC", "Asia/Kolkata", "America/New_York"}) {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone(jvmZone));
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
print("JVM zone " + jvmZone + ", mapper defaults", mapper);
|
||||
}
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
TimeZone india = TimeZone.getTimeZone("Asia/Kolkata");
|
||||
print("JVM zone UTC, defaultTimeZone(Asia/Kolkata)",
|
||||
JsonMapper.builder().defaultTimeZone(india).build());
|
||||
print("defaultTimeZone(Asia/Kolkata), WRITE_DATES_WITH_CONTEXT_TIME_ZONE disabled",
|
||||
JsonMapper.builder().defaultTimeZone(india)
|
||||
.disable(DateTimeFeature.WRITE_DATES_WITH_CONTEXT_TIME_ZONE).build());
|
||||
|
||||
TimeZone london = TimeZone.getTimeZone("Europe/London");
|
||||
Patterned p = new Patterned(Samples.OFFSET, Samples.ZONED);
|
||||
System.out.println("== @JsonFormat(pattern) on offset types, values are at +05:30");
|
||||
System.out.println("mapper zone not set : "
|
||||
+ JsonMapper.builder().build().writeValueAsString(p));
|
||||
System.out.println("defaultTimeZone(Europe/London) : "
|
||||
+ JsonMapper.builder().defaultTimeZone(london).build().writeValueAsString(p));
|
||||
System.out.println("London, CONTEXT_TIME_ZONE disabled: "
|
||||
+ JsonMapper.builder().defaultTimeZone(london)
|
||||
.disable(DateTimeFeature.WRITE_DATES_WITH_CONTEXT_TIME_ZONE).build()
|
||||
.writeValueAsString(p));
|
||||
}
|
||||
|
||||
static void print(String title, JsonMapper mapper) throws Exception {
|
||||
// sql.Date is rebuilt each time: valueOf() reads the JVM zone at construction.
|
||||
Values v = new Values(Samples.WALL, Samples.INSTANT, Samples.OFFSET, Samples.ZONED,
|
||||
Date.from(Samples.INSTANT), java.sql.Date.valueOf(Samples.DAY));
|
||||
System.out.println("== " + title);
|
||||
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(v));
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Per-field formats with the (unchanged) com.fasterxml.jackson.annotation.JsonFormat. */
|
||||
public class T06JsonFormat {
|
||||
public record Invoice(
|
||||
@JsonFormat(pattern = "dd/MM/yyyy") LocalDate issued,
|
||||
@JsonFormat(pattern = "dd-MM-yyyy HH:mm") LocalDateTime dueAt,
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Kolkata") Instant paidAt,
|
||||
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mmXXX",
|
||||
without = JsonFormat.Feature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) OffsetDateTime signedAt,
|
||||
@JsonFormat(pattern = "d MMMM yyyy", locale = "fr_FR") LocalDate printed,
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER) Instant epochSeconds,
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER,
|
||||
without = JsonFormat.Feature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS) Instant writeOnlyMillis,
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER, without = {
|
||||
JsonFormat.Feature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,
|
||||
JsonFormat.Feature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS}) Instant epochMillis,
|
||||
@JsonFormat(shape = JsonFormat.Shape.ARRAY) LocalDate asArray,
|
||||
Month monthDefault,
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING) Month monthName) { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
Invoice invoice = new Invoice(Samples.DAY, Samples.WALL, Samples.INSTANT, Samples.OFFSET,
|
||||
Samples.DAY, Samples.INSTANT, Samples.INSTANT, Samples.INSTANT, Samples.DAY, Month.DECEMBER, Month.DECEMBER);
|
||||
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(invoice);
|
||||
System.out.println(json);
|
||||
System.out.println();
|
||||
Invoice back = mapper.readValue(json, Invoice.class);
|
||||
System.out.println("issued : " + back.issued());
|
||||
System.out.println("dueAt : " + back.dueAt());
|
||||
System.out.println("paidAt : " + back.paidAt());
|
||||
System.out.println("signedAt : " + back.signedAt());
|
||||
System.out.println("printed : " + back.printed());
|
||||
System.out.println("epochSeconds : " + back.epochSeconds());
|
||||
System.out.println("writeOnlyMillis : " + back.writeOnlyMillis());
|
||||
System.out.println("epochMillis : " + back.epochMillis());
|
||||
System.out.println("asArray : " + back.asArray());
|
||||
System.out.println("monthDefault : " + back.monthDefault());
|
||||
System.out.println("monthName : " + back.monthName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.OptBoolean;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Patterns that compile, run, and give the wrong answer or a confusing error. */
|
||||
public class T07FormatTraps {
|
||||
record Default(@JsonFormat(pattern = "yyyy-MM-dd") LocalDate day) { }
|
||||
record StrictY(@JsonFormat(pattern = "yyyy-MM-dd", lenient = OptBoolean.FALSE) LocalDate day) { }
|
||||
record StrictU(@JsonFormat(pattern = "uuuu-MM-dd", lenient = OptBoolean.FALSE) LocalDate day) { }
|
||||
record WeekYear(@JsonFormat(pattern = "YYYY-MM-dd") LocalDate day) { }
|
||||
record CalendarYear(@JsonFormat(pattern = "yyyy-MM-dd") LocalDate day) { }
|
||||
record FakeZ(@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'") LocalDateTime at) { }
|
||||
record NoZone(@JsonFormat(pattern = "yyyy-MM-dd HH:mm") Instant at) { }
|
||||
record ZonedNoZone(@JsonFormat(pattern = "yyyy-MM-dd HH:mm") ZonedDateTime at) { }
|
||||
|
||||
static final JsonMapper MAPPER = JsonMapper.builder().build();
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("== 30 February");
|
||||
read("no pattern ", "\"2026-02-30\"", LocalDate.class);
|
||||
read("pattern ", "{\"day\":\"2026-02-30\"}", Default.class);
|
||||
read("lenient=FALSE, yyyy ", "{\"day\":\"2026-02-30\"}", StrictY.class);
|
||||
read("lenient=FALSE, yyyy ok", "{\"day\":\"2026-02-28\"}", StrictY.class);
|
||||
read("lenient=FALSE, uuuu ", "{\"day\":\"2026-02-30\"}", StrictU.class);
|
||||
read("lenient=FALSE, uuuu ok", "{\"day\":\"2026-02-28\"}", StrictU.class);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== YYYY is the week-based year, yyyy is the calendar year");
|
||||
LocalDate d = LocalDate.of(2026, 12, 29);
|
||||
System.out.println("value 2026-12-29, YYYY : " + MAPPER.writeValueAsString(new WeekYear(d)));
|
||||
System.out.println("value 2026-12-29, yyyy : " + MAPPER.writeValueAsString(new CalendarYear(d)));
|
||||
read("YYYY read ", "{\"day\":\"2026-12-29\"}", WeekYear.class);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== A quoted 'Z' is just a letter");
|
||||
System.out.println("10:30 India wall clock : " + MAPPER.writeValueAsString(new FakeZ(Samples.WALL)));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== A pattern on a type that has no calendar fields");
|
||||
write("Instant, no timezone ", new NoZone(Samples.INSTANT));
|
||||
write("ZonedDateTime ", new ZonedNoZone(Samples.ZONED));
|
||||
read("Instant, no timezone ", "{\"at\":\"2026-12-15 05:00\"}", NoZone.class);
|
||||
read("ZonedDateTime ", "{\"at\":\"2026-12-15 10:30\"}", ZonedNoZone.class);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== Strings that carry more, or less, than the target type");
|
||||
read("LocalDateTime <- ...Z ", "\"2026-12-15T05:00:00Z\"", LocalDateTime.class);
|
||||
read("LocalDateTime <- +05:30", "\"2026-12-15T10:30:00+05:30\"", LocalDateTime.class);
|
||||
read("LocalDate <- date-time", "\"2026-12-15T10:30:00\"", LocalDate.class);
|
||||
read("LocalDate <- ...Z ", "\"2026-12-15T22:30:00Z\"", LocalDate.class);
|
||||
read("Instant <- no offset ", "\"2026-12-15T10:30:00\"", Instant.class);
|
||||
read("LocalDateTime <- space", "\"2026-12-15 10:30:00\"", LocalDateTime.class);
|
||||
read("LocalDate <- \"\" ", "\"\"", LocalDate.class);
|
||||
}
|
||||
|
||||
static void read(String label, String json, Class<?> type) {
|
||||
try {
|
||||
System.out.println(label + " : " + MAPPER.readValue(json, type));
|
||||
} catch (Exception e) {
|
||||
System.out.println(label + " : " + Samples.firstLine(e));
|
||||
}
|
||||
}
|
||||
|
||||
static void write(String label, Object value) {
|
||||
try {
|
||||
System.out.println(label + " : " + MAPPER.writeValueAsString(value));
|
||||
} catch (Exception e) {
|
||||
System.out.println(label + " : " + Samples.firstLine(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** A bare number: seconds or milliseconds? It depends on the target type and one feature. */
|
||||
public class T08EpochNumbers {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper defaults = JsonMapper.builder().build();
|
||||
JsonMapper millis = JsonMapper.builder()
|
||||
.disable(DateTimeFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS).build();
|
||||
String seconds = "1797310800";
|
||||
String ms = "1797310800000";
|
||||
|
||||
System.out.println("expected instant : " + Samples.INSTANT);
|
||||
System.out.println();
|
||||
read("defaults, Instant <- seconds ", defaults, seconds, Instant.class);
|
||||
read("defaults, Instant <- milliseconds ", defaults, ms, Instant.class);
|
||||
read("defaults, Instant <- 1797310800.5 ", defaults, "1797310800.5", Instant.class);
|
||||
read("NANOSECONDS off, Instant <- milliseconds", millis, ms, Instant.class);
|
||||
read("NANOSECONDS off, Instant <- seconds ", millis, seconds, Instant.class);
|
||||
read("defaults, java.util.Date <- milliseconds", defaults, ms, Date.class);
|
||||
read("defaults, java.util.Date <- seconds ", defaults, seconds, Date.class);
|
||||
read("defaults, Instant <- \"1797310800\" ", defaults, "\"1797310800\"", Instant.class);
|
||||
}
|
||||
|
||||
static void read(String label, JsonMapper mapper, String json, Class<?> type) {
|
||||
try {
|
||||
Object value = mapper.readValue(json, type);
|
||||
if (value instanceof Date date) {
|
||||
value = date.toInstant();
|
||||
}
|
||||
System.out.println(label + ": " + value);
|
||||
} catch (Exception e) {
|
||||
System.out.println(label + ": " + Samples.firstLine(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
import tools.jackson.databind.ext.javatime.deser.LocalDateTimeDeserializer;
|
||||
import tools.jackson.databind.ext.javatime.ser.LocalDateTimeSerializer;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.module.SimpleModule;
|
||||
|
||||
/** Three ways to set a format once for the whole mapper, and what each one reaches. */
|
||||
public class T09GlobalFormats {
|
||||
record Row(LocalDate day, LocalDateTime at, Date legacy) { }
|
||||
record Overridden(@JsonFormat(pattern = "yyyyMMdd") LocalDate day, LocalDateTime at, Date legacy) { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Row row = new Row(Samples.DAY, Samples.WALL, Date.from(Samples.INSTANT));
|
||||
|
||||
JsonMapper dateFormat = JsonMapper.builder()
|
||||
.defaultDateFormat(new SimpleDateFormat("dd/MM/yyyy HH:mm"))
|
||||
.build();
|
||||
show("defaultDateFormat(SimpleDateFormat)", dateFormat, row);
|
||||
|
||||
JsonMapper perType = JsonMapper.builder()
|
||||
.withConfigOverride(LocalDate.class,
|
||||
o -> o.setFormat(JsonFormat.Value.forPattern("dd/MM/yyyy")))
|
||||
.withConfigOverride(LocalDateTime.class,
|
||||
o -> o.setFormat(JsonFormat.Value.forPattern("dd/MM/yyyy HH:mm")))
|
||||
.build();
|
||||
show("withConfigOverride per type", perType, row);
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH.mm");
|
||||
SimpleModule module = new SimpleModule()
|
||||
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter))
|
||||
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
|
||||
show("SimpleModule with a DateTimeFormatter",
|
||||
JsonMapper.builder().addModule(module).build(), row);
|
||||
|
||||
System.out.println("== an annotation beats the global override");
|
||||
System.out.println(perType.writeValueAsString(
|
||||
new Overridden(Samples.DAY, Samples.WALL, Date.from(Samples.INSTANT))));
|
||||
}
|
||||
|
||||
static void show(String title, JsonMapper mapper, Row row) throws Exception {
|
||||
System.out.println("== " + title);
|
||||
String json = mapper.writeValueAsString(row);
|
||||
System.out.println(json);
|
||||
System.out.println("read back: " + mapper.readValue(json, Row.class).at());
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Month;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Migration both ways: can each side read what the other wrote? */
|
||||
public class T10StoredPayloads {
|
||||
record Job(Meeting meeting, Duration length, Month month) { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper j2 = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
JsonMapper j3 = JsonMapper.builder().build();
|
||||
Job job = new Job(Samples.meeting(), Duration.ofMinutes(90), Month.DECEMBER);
|
||||
|
||||
String old = j2.writeValueAsString(job);
|
||||
String fresh = j3.writeValueAsString(job);
|
||||
|
||||
System.out.println("== old Jackson 2 payload, read by Jackson 3 defaults");
|
||||
System.out.println(old);
|
||||
attempt(() -> j3.readValue(old, Job.class).toString());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== new Jackson 3 payload, read by a Jackson 2 consumer (defaults + module)");
|
||||
System.out.println(fresh);
|
||||
attempt(() -> j2.readValue(fresh, Job.class).toString());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== Jackson 3 told to keep writing the Jackson 2 shapes");
|
||||
JsonMapper keepOld = JsonMapper.builder()
|
||||
.enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS,
|
||||
DateTimeFeature.WRITE_DURATIONS_AS_TIMESTAMPS)
|
||||
.build();
|
||||
String kept = keepOld.writeValueAsString(job);
|
||||
System.out.println(kept);
|
||||
System.out.println("identical to the Jackson 2 payload : " + kept.equals(old));
|
||||
attempt(() -> j2.readValue(kept, Job.class).toString());
|
||||
}
|
||||
|
||||
interface Call { String run() throws Exception; }
|
||||
|
||||
static void attempt(Call call) {
|
||||
try {
|
||||
System.out.println("OK " + call.run());
|
||||
} catch (Exception e) {
|
||||
System.out.println("FAIL " + Samples.firstLine(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ankurm.javatime;
|
||||
|
||||
import java.time.Month;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.core.JsonGenerator;
|
||||
import tools.jackson.databind.SerializationContext;
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.module.SimpleModule;
|
||||
import tools.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
/** java.time.Month changed from a name to a number, and the number can be off by one. */
|
||||
public class T11MonthTrap {
|
||||
record Report(Month month) { }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper j2 = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
JsonMapper j3 = JsonMapper.builder().build();
|
||||
JsonMapper zeroBased = JsonMapper.builder().disable(DateTimeFeature.ONE_BASED_MONTHS).build();
|
||||
JsonMapper names = JsonMapper.builder()
|
||||
.withConfigOverride(Month.class,
|
||||
o -> o.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING)))
|
||||
.build();
|
||||
Report november = new Report(Month.NOVEMBER);
|
||||
|
||||
System.out.println("value sent : " + november.month());
|
||||
System.out.println("Jackson 2 writes : " + j2.writeValueAsString(november));
|
||||
String fromJ3 = j3.writeValueAsString(november);
|
||||
System.out.println("Jackson 3 defaults write : " + fromJ3);
|
||||
System.out.println(" Jackson 3 reads it : " + j3.readValue(fromJ3, Report.class).month());
|
||||
System.out.println(" Jackson 2 reads it : " + j2.readValue(fromJ3, Report.class).month());
|
||||
String compat = zeroBased.writeValueAsString(november);
|
||||
ObjectMapper j2oneBased = com.fasterxml.jackson.databind.json.JsonMapper.builder()
|
||||
.addModule(new JavaTimeModule()
|
||||
.enable(com.fasterxml.jackson.datatype.jsr310.JavaTimeFeature.ONE_BASED_MONTHS))
|
||||
.build();
|
||||
System.out.println(" Jackson 2 + ONE_BASED_MONTHS reads : " + j2oneBased.readValue(fromJ3, Report.class).month());
|
||||
System.out.println("Jackson 3, ONE_BASED_MONTHS off : " + compat);
|
||||
System.out.println(" Jackson 3 defaults read it : " + j3.readValue(compat, Report.class).month());
|
||||
System.out.println(" Jackson 2 reads it : " + j2.readValue(compat, Report.class).month());
|
||||
String named = names.writeValueAsString(november);
|
||||
System.out.println("Jackson 3, Month override STRING : " + named);
|
||||
System.out.println(" Jackson 3 reads it : " + names.readValue(named, Report.class).month());
|
||||
System.out.println(" Jackson 2 reads it : " + j2.readValue(named, Report.class).month());
|
||||
|
||||
SimpleModule module = new SimpleModule().addSerializer(Month.class, new MonthNameSerializer());
|
||||
System.out.println("Jackson 3, MonthNameSerializer : "
|
||||
+ JsonMapper.builder().addModule(module).build().writeValueAsString(november));
|
||||
}
|
||||
|
||||
/** Works on every 3.x line tried here, including the one Spring Boot 4.2.0 manages. */
|
||||
static final class MonthNameSerializer extends StdSerializer<Month> {
|
||||
MonthNameSerializer() {
|
||||
super(Month.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(Month value, JsonGenerator gen, SerializationContext context) {
|
||||
gen.writeString(value.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user