Reputation: 113
I would like to make a REST call to a partner system, with Json object in the body. We use ZonedDateTime, and I need to send the dates in the format "2025-01-05T21:41:24.195Z".
Currently it is serialized to the format "2025-01-03T12:46:09.00688+01:00".
I have the following configuration:
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer(DateTimeFormatter.ISO_INSTANT));
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return objectMapper;
}
I inject this objectMapper into my service and expected this to serialize the date in the correct format, but it is not enough.
EDIT: I don't know what happened, how or why, but after truncating the ZonedDateTime, my REST call is accepted.
Upvotes: 1
Views: 101
Reputation: 4410
This approach works:
@Test
void test() throws Exception {
var formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendInstant(3)
.toFormatter();
var serializer = new ZonedDateTimeSerializer(formatter);
var javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class, serializer);
var objectMapper = new ObjectMapper();
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
var str = objectMapper.writeValueAsString(ZonedDateTime.now());
System.out.println(str);
}
The test prints
"2025-01-06T16:32:37.855Z"
I think you should make sure the mapper injected into your target bean is the one you are configuring and not e.g. the default mapper created by Jackson. Try this:
@Bean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
var formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendInstant(3)
.toFormatter();
var serializer = new ZonedDateTimeSerializer(formatter);
var javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(ZonedDateTime.class, serializer);
return builder
.modules(javaTimeModule)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
Pay attention to method (bean) name.
P.S. There's JacksonAutoConfiguration.JacksonObjectMapperConfiguration
providing the declaration of ObjectMapper
:
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
static class JacksonObjectMapperConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean
ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.createXmlMapper(false).build();
}
}
This is where the default mapper is created. To override it you need to declare your own ObjectMapper with the same name and type which will be used for HTTP response serialization.
Upvotes: 2