Home >Java >javaTutorial >How to Properly Format Java 8 LocalDate Objects in JSON using Jackson?
Formatting Java 8 LocalDate with Jackson
Problem:
In Java applications, converting Date objects into JSON format with specific date patterns can be straightforward using the @JsonFormat annotation. However, when dealing with java.time.LocalDate introduced in Java 8, the same approach may not work as expected.
Proposed Solution:
To customize the formatting of LocalDate objects for JSON serialization, the following approach can be used:
Example Code:
ContextResolver:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Provider public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { @Override public ObjectMapper getContext(Class<?> type) { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); return mapper; } }
Resource Class:
import java.time.LocalDate; @Path("person") public class LocalDateResource { @GET public Person getPerson() { return new Person(LocalDate.now()); } }
Person Class:
public class Person { @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) private LocalDate birthDate; }
By implementing this approach, LocalDate objects can be serialized and deserialized effectively, enabling flexible JSON formatting.
The above is the detailed content of How to Properly Format Java 8 LocalDate Objects in JSON using Jackson?. For more information, please follow other related articles on the PHP Chinese website!