Jackson date-format for OffsetDateTime in Spring Boot
So I've managed to figure out a solution, but if you have an alternative please post it.
I ended up creating a new primary ObjectMapper
bean, and registering a new module with a custom serializer for OffsetDateTime
. I'm able to set my own date format in here, using java.time.format.DateTimeFormatter
. I also had to register the JavaTimeModule
with my mapper.
@Configuration
public class JacksonOffsetDateTimeMapper{
@Primary
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() {
@Override
public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(offsetDateTime));
}
});
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
By doing that, you can get OffsetDateTime properties as ISO 8601 including offset in your target.