问题
I recently tried to implement a micro service using spring-boot 2.
Now, whenever I attempt to return an object which contains a java.time.LocalDateTime
from my REST service, the LocalDateTime get serialized as an array of integers. Like so:
{
"id": "5bf1425f9f8de267f04b22ad",
"description": "aaaaaarrrgggghhhhh",
"timestamp": [
2018,
11,
18,
11,
43,
43,
889000000
],
"time": 2.25,
...
}
I have tried configuring the ObjectMapper
through settings in application.yml
spring:
jackson:
serialization:
write-dates-as-timestamps: false
but doesn't work. I have also tried configuring a new ObjectMapper through a Spring Configuration class, like so:
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
final ObjectMapper objectMapper = builder.build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
My configuration gets loaded (debugger stops at a breakpoint) - it's just that it does nothing.
I tried adding jackson
dependencies manually (also for the jsr310 module) to my pom.xml - also without any luck.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
For some reason it looks like Spring Boot is ignoring my attempts to anything with the ObjectMapper, and it keeps returning the same result.
Setting log level to DEBUG for com.fasterxml
in the application.yml
also yields no output:
logging:
level:
com.fasterxml: DEBUG
I use Spring Boot 2.1.0-RELEASE with Jackson 2.9.7.
The basic pom file was generated from https://start.spring.io My project compiles for and runs on a Java 8 JVM.
回答1:
This answer is based on teppic's comment to the original post.
The issue was caused by @EnableWebMVC on one of my @Configuration classes. Removed @EnableWebMVC immediately solved the problem.
回答2:
From your comments I found the issue as you blend the @EnableWebMvc
with sprongboot. It turns out that Spring Boot doesn’t mix well with the standard Spring MVC @EnableWebMvc
. What happens when you add the annotation is that spring boot autoconfiguration is disabled.
回答3:
You must add jsr310 support to jackson :
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
来源:https://stackoverflow.com/questions/53364800/spring-boot-2-not-serializing-localdatetime