For those of you that were not able to get the [.SSS]
solution to work, here is what I ended up doing.
Retain the @JsonFormat
annotation on your field for serialization, but build a custom deserializer for parsing Dates which might not have the milliseconds portion specified. Once you implement the deserializer you will have to register it with your ObjectMapper
as a SimpleModule
class DateDeserializer extends StdDeserializer<Date> {
private static final SimpleDateFormat withMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
private static final SimpleDateFormat withoutMillis = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
public DateDeserializer() {
this(null);
}
public DateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String dateString = p.getText();
if (dateString.isEmpty()) {
//handle empty strings however you want,
//but I am setting the Date objects null
return null;
}
try {
return withMillis.parse(dateString);
} catch (ParseException e) {
try {
return withoutMillis.parse(dateString);
} catch (ParseException e1) {
throw new RuntimeException("Unable to parse date", e1);
}
}
}
}
Now that you have a custom deserializer, all that is left is to register it. I am doing so with a ContextResolver<ObjectMapper>
that I already had in my project, but however you work with your ObjectMapper
should be fine.
@Provider
class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
SimpleModule dateModule = new SimpleModule();
dateModule.addDeserializer(Date.class, new DateDeserializer());
mapper.registerModule(dateModule);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}