Jackson ObjectMapper.findAndRegisterModules() not working to serialise LocalDateTime

6.4k Views Asked by At

I am using Java Spring-boot RestController. I have a sample GET API in which I am sending LocalDateTime.now() in response body. I have customised the Jackson ObjectMapper to register jackson-datatype-jsr310 module, However it fails to serialise the LocalDateTime instance. I have tried many different solutions available online, however nothing seems to work. The solution that I had before posting here is mentioned below.

The GET API gives the following error:

"Java 8 date/time type java.time.LocalDateTime not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: org.springframework.http.ResponseEntity["body"])"

Code:

ObjectMapper Configuration:

@Configuration
public class JacksonConfiguration {
    @Bean
    @Primary
    public ObjectMapper objectMapper2(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.findAndRegisterModules();
        return objectMapper;
    }
}

Note: I have tried using objectMapper.registerModule(new JSR310Module()) and objectMapper.registerModule(new JavaTimeModule()). They don't work either.

Rest Controller:

@RestController
public class TestController {
    @GetMapping("/test")
    public ResponseEntity<Object> test() {
        return ResponseEntity.ok().body(LocalDateTime.now());
    }
}

I am using spring-boot-starter-parent 2.5.4, so it automatically uses version 2.12.4 for all jackson.* dependencies including jackson-datatype-jsr310.

1

There are 1 best solutions below

4
dariosicily On

Welcome to Stack Overflow, like documented at datetime the lines ObjectMapper objectMapper = builder.build();objectMapper.findAndRegisterModules(); you are currently using are valid just for jackson 2.x before 2.9 while your project includes the jackson 2.12.4 library : like the official documentation I linked before you have to use instead the following code :

// Jackson 2.10 and later
ObjectMapper mapper = JsonMapper.builder()
    .findAndAddModules()
    .build();

Or as an alternative if you prefer to selectively register the JavaTimeModule module :

// Jackson 2.10 and later:
ObjectMapper mapper = JsonMapper.builder()
    .addModule(new JavaTimeModule())
    .build();

Update : I modified the original code proposed in the question to the following :

@Configuration
public class JacksonConfiguration {
    @Bean
    @Primary
    public ObjectMapper objectMapper2(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper mapper = JsonMapper.builder()
                .addModule(new JavaTimeModule())
                .build();
        return mapper;
    }
}

The javatime module works fine and returns the correct LocalTime json representation; without the configuration class the returned value is the correct iso string.