ran*_*m86 4 java datetime spring-mvc jodatime jackson
我正在尝试在我的Web应用程序中配置ObjectMapper以序列化/反序列化以ISO 8601格式呈现为Joda的DateTime的日期.我找到了有用的库jackson-datatype-joda和它的模块,JodaModule所以我添加了依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.4.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我的Spring配置:
<bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true">
<property name="featuresToDisable">
<array>
<util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</array>
</property>
<property name="modulesToInstall" value="com.fasterxml.jackson.datatype.joda.JodaModule" />
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)
当我尝试序列化这个bean时
public class Bean {
private DateTime start = new DateTime();
public DateTime getStart() { return start; }
public void setStart(DateTime start) { this.start = start; }
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出,但希望它是ISO 8601格式:
{"start":1418337158933}
我发现JodaModule如果在类路径中找到它也会预加载,因此无需手动注册它(请参阅github repo),但在应用程序启动期间会多次调用此代码.
我认为原因是ObjectMapper在其他地方实例化.
更新:问题是还有一个文件使用Spring配置声明了ObjectMapper.答案中给出的两个解决方案都有效.干杯!
如果您在下面的代码中创建自定义ObjectMapper类,它将覆盖默认的objectMapper,您根本不需要xml配置:
@Service
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
this.registerModule(new JodaModule());
}
}
Run Code Online (Sandbox Code Playgroud)
我已经将这个简单的服务添加到简单的spring启动应用程序中,并且以预期的格式获得了时间.