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:
2026-12-03 23:41:03 +05:30
co-authored by Claude Sonnet 5.5
parent f5ed5d1605
commit 26f64bc184
42 changed files with 1505 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
<relativePath/>
</parent>
<groupId>com.ankurm</groupId>
<artifactId>java-time-boot</artifactId>
<version>1.0.0</version>
<name>java-time-boot</name>
<properties>
<java.version>25</java.version>
</properties>
<dependencies>
<!-- Brings in spring-boot-starter-jackson; the Jackson 3 version comes from the Boot BOM. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,80 @@
package com.ankurm.javatime.boot;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.ConfigurableApplicationContext;
import tools.jackson.databind.json.JsonMapper;
/** Starts the app once per configuration on a random port and calls it over real HTTP. */
public class BootDemo {
static final HttpClient HTTP = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Spring Boot " + SpringBootVersion.getVersion()
+ ", Jackson " + tools.jackson.databind.cfg.PackageVersion.VERSION);
run("no spring.jackson.* properties");
run("write-dates-as-timestamps",
"--spring.jackson.datatype.datetime.write-dates-as-timestamps=true");
run("date-format", "--spring.jackson.date-format=dd/MM/yyyy HH:mm");
run("time-zone", "--spring.jackson.time-zone=Asia/Kolkata");
run("keep the client's offset",
"--spring.jackson.datatype.datetime.adjust-dates-to-context-time-zone=false");
run("use-jackson2-defaults", "--spring.jackson.use-jackson2-defaults=true");
run("spring.mvc.format.date", "--spring.mvc.format.date=dd/MM/yyyy");
run("profile indian-dates (JsonMapperBuilderCustomizer)", "--spring.profiles.active=indian-dates");
run("profile recommended (application-recommended.yml)", "--spring.profiles.active=recommended");
run("Boot 3 property name left in place",
"--spring.jackson.serialization.write-dates-as-timestamps=false");
}
static void run(String title, String... properties) throws Exception {
System.out.println();
System.out.println("==== " + title);
for (String p : properties) {
System.out.println(p.substring(2));
}
List<String> args = new ArrayList<>(List.of(properties));
args.add("--server.port=0");
args.add("--spring.main.banner-mode=off");
args.add("--logging.level.root=OFF");
try (ConfigurableApplicationContext context =
SpringApplication.run(DemoApplication.class, args.toArray(String[]::new))) {
String base = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");
call("GET /event", HttpRequest.newBuilder(URI.create(base + "/event")).build());
call("POST /booking", HttpRequest.newBuilder(URI.create(base + "/booking"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"startsAt\":\"2026-12-15T10:30:00+05:30\"}"))
.build());
call("GET /search?day=2026-12-15", HttpRequest.newBuilder(URI.create(base + "/search?day=2026-12-15")).build());
call("GET /search?day=15/12/2026", HttpRequest.newBuilder(URI.create(base + "/search?day=15/12/2026")).build());
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println("startup FAILED: " + e.getClass().getSimpleName());
System.out.println("root cause : " + root.getClass().getSimpleName() + ": " + root.getMessage());
}
}
static void call(String label, HttpRequest request) throws Exception {
HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
String body = response.body();
if (response.statusCode() != 200) {
body = "(" + JsonMapper.shared().readTree(body).path("error").asString() + ")";
}
System.out.println(label + " -> " + response.statusCode() + " " + body);
}
}
@@ -0,0 +1,7 @@
package com.ankurm.javatime.boot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
class DemoApplication {
}
@@ -0,0 +1,47 @@
package com.ankurm.javatime.boot;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** Demo endpoints: one writes date types, one reads them from a body, one from a query string. */
@RestController
class EventController {
record Event(LocalDate day, LocalDateTime wallClock, Instant createdAt,
OffsetDateTime startsAt, Duration length, Month month, Date legacy) { }
record Booking(OffsetDateTime startsAt) { }
@GetMapping("/event")
Event event() {
LocalDateTime wall = LocalDateTime.of(2026, 12, 15, 10, 30);
OffsetDateTime start = wall.atOffset(ZoneOffset.ofHoursMinutes(5, 30));
return new Event(wall.toLocalDate(), wall, start.toInstant(), start,
Duration.ofMinutes(90), Month.NOVEMBER, Date.from(start.toInstant()));
}
/** Shows what the controller actually receives after Jackson has read the body. */
@PostMapping("/booking")
Map<String, String> booking(@RequestBody Booking booking) {
return Map.of("received", booking.startsAt().toString());
}
/** A query parameter is converted by Spring MVC, not by Jackson. */
@GetMapping("/search")
Map<String, String> search(@RequestParam LocalDate day) {
return Map.of("parsed", day.toString());
}
}
@@ -0,0 +1,39 @@
package com.ankurm.javatime.boot;
import java.time.LocalDate;
import java.time.Month;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ext.javatime.deser.LocalDateDeserializer;
import tools.jackson.databind.module.SimpleModule;
import tools.jackson.databind.ser.std.StdSerializer;
/** Global rules that properties cannot express. Active with the "indian-dates" profile. */
@Configuration(proxyBeanMethods = false)
@Profile("indian-dates")
class IndianDatesCustomizer {
@Bean
JsonMapperBuilderCustomizer indianDates() {
// Month by name, with a serializer because the Jackson that Boot 4.2.0 manages
// ignores a STRING shape override for Month.
SimpleModule months = new SimpleModule().addSerializer(Month.class, new StdSerializer<Month>(Month.class) {
@Override
public void serialize(Month value, JsonGenerator gen, SerializationContext context) {
gen.writeString(value.name());
}
});
return builder -> builder
.withConfigOverride(LocalDate.class,
o -> o.setFormat(JsonFormat.Value.forPattern("dd/MM/yyyy")))
.addModule(months);
}
}
@@ -0,0 +1,12 @@
# A starting point for a new Spring Boot 4 API. Active with the "recommended" profile.
spring:
jackson:
datatype:
datetime:
# Hand controllers the offset the client sent instead of converting it to the mapper zone.
adjust-dates-to-context-time-zone: false
mvc:
format:
# Query and path parameters are not read by Jackson; state their format separately.
date: iso
date-time: iso