Home >Java >javaTutorial >How Can I Format LocalDate with Jackson in Java 8?
When dealing with java.util.Date, the @JsonFormat annotation provides convenient formatting. However, for Java 8's LocalDate field, using custom serializers and deserializers may not suffice.
To achieve the desired formatting, a more comprehensive approach is recommended. By introducing the Jackson JSR310Module, additional functionalities become available.
First, add the Jackson dependency:
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.4.0</version> </dependency>
Note: Ensure that the included dependency versions are aligned to avoid potential class resolution conflicts.
Next, define a ContextResolver for ObjectMapper:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @Provider public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final ObjectMapper MAPPER; public ObjectMapperContextResolver() { MAPPER = new ObjectMapper(); MAPPER.registerModule(new JavaTimeModule()); MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } @Override public ObjectMapper getContext(Class<?> type) { return MAPPER; } }
In the resource class, utilize the ObjectMapperContextResolver:
@Path("person") public class LocalDateResource { @GET @Produces(MediaType.APPLICATION_JSON) public Response getPerson() { Person person = new Person(); person.birthDate = LocalDate.now(); return Response.ok(person).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response createPerson(Person person) { return Response.ok( DateTimeFormatter.ISO_DATE.format(person.birthDate)).build(); } public static class Person { public LocalDate birthDate; } }
Request:
curl -v http://localhost:8080/api/person
Result:
{"birthDate":"2015-03-01"}
Post Request:
curl -v -POST -H "Content-Type:application/json" -d "{\"birthDate\":\"2015-03-01\"}" http://localhost:8080/api/person
Post Result:
2015-03-01
By employing JSR310Module, ObjectMapperContextResolver, and setting SerializationFeature.WRITE_DATES_AS_TIMESTAMPS to false, Java 8's LocalDate can be formatted effectively with Jackson.
The above is the detailed content of How Can I Format LocalDate with Jackson in Java 8?. For more information, please follow other related articles on the PHP Chinese website!