I'm trying to output an OffsetDateTime from my Spring application, and have in my application.properties these properties:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false spring.jackson.date-format=yyyy-MM-dd'T'HH:mm
However when the date is returned it is formatted as
"2017-01-30T16:55:00Z"
How should I correctly configure the format for the date in my Spring application?
If your date is argument to a function, you can use @DateTimeFormat(pattern = "yyyy-MM-dd") to define a pattern (ie. org. springframework. format.
It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).
How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.
We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With