Explain Codes LogoExplain Codes Logo

Json Java 8 LocalDateTime format in Spring Boot

java
objectmapper
jackson
datetime
Anton ShumikhinbyAnton Shumikhin·Nov 2, 2024
TLDR

To achieve the proper serialization of LocalDateTime in Spring Boot, start by adding @JsonFormat annotation to your model attributes and stipulate the pattern you favor. For instance, for "year-month-day hours:minutes:seconds" format, use @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss"). To assure the compatibility of Java 8 date/time API, ensure the module jackson-datatype-jsr310 is on your classpath.

import com.fasterxml.jackson.annotation.JsonFormat; import java.time.LocalDateTime; public class SampleModel { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // Your date will look like a secret agent code! private LocalDateTime dateTime; // ... getters and setters ... }

In your pom.xml, include:

<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.9.0</version> <!-- The version that suits your boot as much it suits Cinderella! --> </dependency>

Don't let your dates transform into numeric horrors. Add this to your application.properties:

spring.jackson.serialization.write_dates_as_timestamps=false // Because who needs another reason to scream at their screen, right?

Using this property ensures LocalDateTime in your JSON output is formatted properly with Spring Boot 2.x, sans any extra configuration.

From zero to hero: Advanced configuration

Defining date-time formats globally

What if you'd like a jack-of-all-trades date format for all LocalDateTime fields? You can achieve this by adjusting your ObjectMapper in a configuration class:

import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { return builder .serializers(new LocalDateTimeSerializer()) .deserializers(new LocalDateTimeDeserializer()) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // Because the ghosts of JSON past shall haunt no more! .build(); } }

Custom date-time format strategy

You might need custom serialization and deserialization approaches for that peculiarly formatted date-time. Implement LocalDateTimeSerializer and LocalDateTimeDeserializer.

For serialization:

public class CustomLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> { private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(value.format(formatter)); // Now you can stay cryptic with your date and time formats. } }

For deserialization:

public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> { private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); @Override public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { return LocalDateTime.parse(p.getValueAsString(), formatter); // Because who doesn't love a magic trick with dates? } }

Compatibility is a virtue

Ensure your jackson-datatype-jsr310 module version meshes with your Spring Boot to avert issues, especially when juggling different versions of libraries, or when embarking on Spring Boot's upgrade journey.

Resolving annotation feuds

Annotations like @JsonFormat and @DateTimeFormat have precise roles. Ensure understanding these contexts and resolving their conflicts. @DateTimeFormat comes in handy for LocalDate fields binding on HTTP requests, while @JsonFormat is utilized for JSON serialization/deserialization.

Unraveling the serialization mystery

Got tangled up in LocalDateTime serialization? Common culprits are:

  • Dependency version: missing or incorrect.
  • Annotations: conflicting.
  • ObjectMapper: misconfigured.

To mend these cracks:

  1. Double-check dependencies and their versions.
  2. Ensure correct usage of annotations.
  3. Improve your ObjectMapper configuration. Make sure WRITE_DATES_AS_TIMESTAMPS is off the board.

Master the art of robust configuration

For low-maintenance and robust configuration:

  • Keep updated with dependencies and your Spring Boot version.
  • Opt for the global settings in application.properties or through an ObjectMapper bean for uniform behavior.
  • Use field-specific annotations sparingly and only when necessary.

Expanding your date-time horizons

A few tips when dealing with date-time in Java 8 and Spring Boot:

  • Be a smart traveler: be timezone aware.
  • Learn about other date-time classes like ZonedDateTime or OffsetDateTime.
  • Make test driven development your mantra. Let integrations and unit tests verify your date-time formatting.