Where is the place to register a Jackson Codec in Vertx 4.0 using custom Object Mapper

4.2k views Asked by At

I am trying to convert my Quarkus vertex sample to pure Vertx 4.0 and encountered a problem.

In Quarkus, it is easy to customize the Jackson ObjectMapper to serialize or deserialize the HTTP messages.


@ApplicationScoped
public class CustomObjectMapper implements ObjectMapperCustomizer {

    @Override
    public void customize(ObjectMapper objectMapper) {
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
        objectMapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);

        JavaTimeModule module = new JavaTimeModule();
        LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
        objectMapper.registerModule(module);
    }
}

And in Vertx, how to customize the ObjectMapper gracefully? My intention is registering a custom ObjectMapper instead of the built-in one, thus when using Json.encode, it will use my custom objectMapper instead.

In my Vertx sample, the Json.encode will use the built-in objectMapper to serialize the Java 8 DateTime to an int array instead of an ISO date string.

1

There are 1 answers

2
tsegismont On BEST ANSWER

First, you need to add jackson-databind to your dependencies because Vert.x 4 does not bring transitively.

Then in your main method:

io.vertx.core.json.jackson.DatabindCodec codec = (io.vertx.core.json.jackson.DatabindCodec) io.vertx.core.json.Json.CODEC;
// returns the ObjectMapper used by Vert.x
ObjectMapper mapper = codec.mapper();
// returns the ObjectMapper used by Vert.x when pretty printing JSON
ObjectMapper prettyMapper = codec.prettyMapper();

Now you can configure both mappers