I'm parsing a ZonedDateTime
using like this:
@JsonSerialize(using = ZonedDateTimeSerializer.class)
private ZonedDateTime expirationDateTime;
I need to be able to properly deserialize this date. However, there is no deserializer for this that is provided by jackson:
com.fasterxml.jackson.datatype.jsr310.deser
Is there a reason why it's missing? What is the most common workaround?
Updated: Here is my scenario:
I create ZonedDateTime
like this:
ZonedDateTime.of(2017, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC)
Then I serialize the object that contains the date like this:
public static String toJSON(Object o) {
ObjectMapper objectMapper = new ObjectMapper();
StringWriter sWriter = new StringWriter();
try {
JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(sWriter);
objectMapper.writeValue(jsonGenerator, o);
return sWriter.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
And when I try to send it to Spring MVC Controller:
mockMvc.perform(post("/endpoint/")
.content(toJSON(myObject))
.contentType(APPLICATION_JSON))
.andExpect(status().isOk());
The date object that goes inside the controller is different.
Before: 2017-01-01T01:01:01.000000001Z
After: 2017-01-01T01:01:01.000000001Z[UTC]
The 2 values
2017-01-01T01:01:01.000000001Z
and2017-01-01T01:01:01.000000001Z[UTC]
actually represent the same instant, so they are equivalent and can be used without a problem (at least there should be no problems as they represent the same instant).The only detail is that Jackson, for some reason, sets the
ZoneId
value to "UTC" when deserializing, which is redundant in this case (theZ
already tells that the offset is "UTC"). But it shouldn't affect the date value itself.A very simple way to get rid of this
[UTC]
part is to convert this object toOffsetDateTime
(so it keeps theZ
offset and don't use the[UTC]
zone) and then back again toZonedDateTime
:After that, the value of
z
variable will be2017-01-01T01:01:01.000000001Z
(without the[UTC]
part).But of course this is not ideal as you'd have to do it manually for all dates. A better approach is to write a custom deserializer (by extending
com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer
) that don't set the timezone when it's UTC:Then you have to register this deserializer. If you use
ObjectMapper
, you need to add this to theJavaTimeModule
:If you configure it in Spring, the config will be something like this (not tested):
I use this :