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.LocalDateTimenot 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.
Welcome to Stack Overflow, like documented at
datetimethe linesObjectMapper 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 :Or as an alternative if you prefer to selectively register the JavaTimeModule module :
Update : I modified the original code proposed in the question to the following :
The javatime module works fine and returns the correct
LocalTimejson representation; without the configuration class the returned value is the correct iso string.