September 23, 2014

Java 8 LocalDate with Jackson Serialize and Deserialize Example - RESTful WS

Although I having using Joda Time for years, it is now time to migrate over to the Java 8 Date and Time API (JSR310), and make use of the new LocalDate and LocalTime classes.

WildFly 8.1.0 uses Jackson 2.3.2 which does not know how to (de)serialize the JSR310 Date Time classes. So in order to use the Date and Time API we need to add a Jackson third party datatype dependency to our pom:
<dependency>
    <groupid>com.fasterxml.jackson.datatype</groupid>
    <artifactid>jackson-datatype-jsr310</artifactid>
    <version>2.4.0</version>
</dependency>
Then to deserialize your LocalDate add the @JsonDeserialize annotation and use the LocalDateDeserializer:
@Path("/resource")
@Produces("application/json")
public class MyRestResource {

    @GET
    @Path("now")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    public LocalDate get() {
        return LocalDate.now();
    }
}
To serialize your LocalDate add @JsonSerialize annotation and use the LocalDateSerializer:
@JsonSerialize(using = LocalDateSerializer.class)

To create your own serializer/deserializer check this example, which shows you how you can format the date.

No comments :

Post a Comment