Search code examples
javajava-timeobjectmapperjackson2

Register JavaTimeModule with the default objectmapper in springboot


I define a JavaTimeModule:

@Bean public Module java8TimeModule() {
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    return javaTimeModule; 
}

However, it does not register itself with the default objectmapper. I am using jackson-databind-2.8.9.jar.

The online help of JavaTimeModule() in Eclipse IDE says that:

Note that as of 2.6, this module does NOT support auto-registration.

Not sure if it is still the same case for jackson-databind-2.8.9 causing JavaTimeModule not registering with the default objectmapper.

I do not want to create a new objectmapper. As in the past when I tried this, I had another issue with the objectmapper I created.

Springboot doc says:

Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper.

But I could not find code examples and not sure how to do it.

If I define a @Bean of type Jackson2ObjectMapperBuilder, will it replace the default one? What is the consequence of it? And how to get the default objectmapper from Jackson2ObjectMapperBuilder?


Solution

  • I found an existing link on how to customize the default objectMapper at Jackson2ObjectMapperBuilder enable field visibility ANY.

    I also found out the problem in my program. The JavaTimeModule is automatically registered with the default objectMapper with jackson-databind-2.8.9. The issue in my program is caused by using a newly created objectMapper. I should have used the default objectMapper by @Autowired objectMapper.