Pete
Pete

Reputation: 10918

Jackson JSON deserialization to java.util.Date not working

We are trying to send java.util.Date objects to our REST resource but Jackson deserializes the JSON string for the incoming date 1348696800000 to a Date with the value 163469056-01-01 00:00:00.0. What could be the problem?

Our REST resource:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(A a) {
}

The POJO:

@XmlRootElement(name = "A")
public class A {
    private Date startDate;
}

The JSON:

{ ... "startDate":1348696800000, ... }

If Jackson serializes a Date into Milliseconds it should be able to deserialize it again.. I really don't want to write a custom deserializer for this which I then have to declare for every Date property on client and server side..

Upvotes: 0

Views: 3503

Answers (1)

Pete
Pete

Reputation: 10918

So we decided to work around the problem and have our client create formatted date strings to send to the REST server using a custom

public class JsonDateSerializer extends JsonSerializer<Date> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        String formattedDate = dateFormat.format(date);

        gen.writeString(formattedDate);
    }

Upvotes: 1

Related Questions