Issue
How can I configure webflux to serialize java.time (specifically Instant) as a ISO date string?
With below code I get:
{"id":"id","timestamp":1606890022.131813600}
{"id":"id","timestamp":"2020-12-02T07:20:16.553Z"}
@EnableWebFlux
@SpringBootApplication
public class WebfluxJavaTimeSerializationApplication {
public static void main(String[] args) {
SpringApplication.run(WebfluxJavaTimeSerializationApplication.class, args);
}
@Bean
public RouterFunction<?> routerFunction() {
return route().GET("/resource", request -> ServerResponse.ok().body(Mono.just(new Resource()),Resource.class)).build();
}
public class Resource {
String id = "id";
Instant timestamp = Instant.now();
public String getId() {
return id;
}
public Instant getTimestamp() {
return timestamp;
}
}
}
I've tried configurations like:
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {
//moved from application class
@Bean
public RouterFunction<?> routerFunction() {
return route().GET("/resource", request -> ServerResponse.ok().body(Mono.just(new Resource()), Resource.class)).build();
}
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
@Override
public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper));
configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper));
}
}
but it does not change the response. I believe formatters are only used for deserialization and codecs for the WebClient (but might be mistaken).
Solution
You are disabling the auto-configuration of Jackson and WebFlux due to having added @EnableWebFlux
. With this Spring Boot will back-off in configuring things, one of those things is a fully pre-configured Jackson.
So try not to outsmart the defaults in this case.
Remove the @EnableWebFlux
and also remove the specific formatting for Jackson. You could actually remove the implements WebFluxConfigurer
and remove the overridden methods.
Answered By - M. Deinum
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)