Home >Java >javaTutorial >How Can I Format Java 8's LocalDate with Jackson Without Annotations?
Formatting Java 8's LocalDate with Jackson
Jackson's annotation-based formatting for java.util.Date extends seamlessly to LocalDate fields in Java 8. To achieve this, avoid using annotations and instead employ Jackson's ContextResolver in conjunction with the JavaTimeModule.
ContextResolver:
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; } }
Resource Class:
import java.time.LocalDate; @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; } }
Testing:
Using this approach, you should be able to serialize and deserialize LocalDate values as JSON strings using the ISO-8601 format.
For more information, refer to the JSR310 module documentation.
Note:
As of Jackson version 2.7, the JSR310Module is deprecated. Use the JavaTimeModule instead.
The above is the detailed content of How Can I Format Java 8's LocalDate with Jackson Without Annotations?. For more information, please follow other related articles on the PHP Chinese website!