7

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.

Hantsy
  • 8,006
  • 7
  • 64
  • 109

1 Answers1

5

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

tsegismont
  • 8,591
  • 1
  • 17
  • 27
  • Vertx configured a `DatabindCodec`(of course, I included databind, and jsr310 module) using JacksonFactory which defined an `ObjectMapper` there. I do not know how to configure it. For my application, when I call `Json` methods in the handlers, the Java 8 Datetime is not serialized to a string but an int array(it is a general problem in Java can be fixed by adjusting the parameters of ObjectMapper). – Hantsy Dec 11 '20 at 02:17
  • 1
    For me (VertX 4.0.3) `mapper()` and `prettyMapper()` are static methods on `DatabindCodec`. So accessing the `Json` class and casting the codec seems unnecessary. You can access the mapper directly, e.g. `DatabindCodec.mapper()`. – stempler May 05 '21 at 07:39