在我的Spring Boot项目中,似乎没有spring.jackson属性正常工作。我想控制日期字段,我尝试将以下属性添加到我的application.properties文件中:
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.joda-date-time-format=yyyy-MM-dd HH:mm:ss
日期仍然是时间戳(java.util.Date和joda.time)。我有以下依赖项:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
我没有添加版本号,但它表示托管版本号为2.8.7(全部为3)。
如果我在任何课程中使用@EnableWebMvc
注释,我已经阅读了它,它不会起作用。但是我没有使用这样的注释。 (但是我的classpath上有spring-webmvc。)
当我启动应用程序(在Tomcat中)时,我收到了这些日志消息:
2017-04-23 16:54:55 DEBUG JndiTemplate:150 - Looking up JNDI object with name [java:comp/env/spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS]
2017-04-23 16:54:55 DEBUG JndiLocatorDelegate:101 - Converted JNDI name [java:comp/env/spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS] not found - trying original name [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS]. javax.naming.NameNotFoundException: Name [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS] is not bound in this Context. Unable to find [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS].
2017-04-23 16:54:55 DEBUG JndiTemplate:150 - Looking up JNDI object with name [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS]
2017-04-23 16:54:55 DEBUG JndiPropertySource:99 - JNDI lookup for name [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS] threw NamingException with message: Name [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS] is not bound in this Context. Unable to find [spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS].. Returning null.
2017-04-23 16:54:55 DEBUG PropertySourcesPropertyResolver:151 - Found key 'spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS' in [URL [file:C:/Program Files/Apache Software Foundation/Tomcat 9.0/conf/Catalina/localhost/Blowfish/config/application.properties]] with type [String]
只有一件事适用于java.util.Date和joda.time:
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter{
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
MappingJackson2HttpMessageConverter jsonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
}
}
}
}
但我不喜欢这个解决方案,在我的application.properties中使用一些配置会更优雅。
我使用Spring Boot 1.5.2。