根据http://wiki.fasterxml.com/JacksonFAQDateHandling,"DateTime可以自动序列化/反序列化,类似于处理java.util.Date的方式."但是,我无法完成此自动功能.有关于此主题的StackOverflow讨论,但大多数涉及基于代码的解决方案,但基于上面的引用,我应该能够通过简单的配置来实现这一点.
根据http://wiki.fasterxml.com/JacksonFAQDateHandling我有我的配置集,以便将日期写为时间戳为false.结果是java.util.Date类型被序列化为ISO 8601格式,但org.joda.time.DateTime类型被序列化为长对象表示.
我的环境是这样的:
Jackson 2.1
Joda时间2.1
Spring 3.2
Java 1.6
我的jsonMapper bean的Spring配置是
@Bean
public ObjectMapper jsonMapper() {
ObjectMapper objectMapper = new ObjectMapper();
//Fully qualified path shows I am using latest enum
ObjectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS , false);
return objectMapper;
}
Run Code Online (Sandbox Code Playgroud)
我的测试代码片段是这样的
Date d = new Date();
DateTime dt = new DateTime(d); //Joda time
Map<String, Object> link = new LinkedHashMap<String, Object>();
link.put("date", d);
link.put("createdDateTime", dt);
Run Code Online (Sandbox Code Playgroud)
生成的JSON输出片段是这样的:
{"date":"2012-12-24T21:20:47.668+0000"}
{"createdDateTime": {"year":2012,"dayOfMonth":24,"dayOfWeek":1,"era":1,"dayOfYear":359,"centuryOfEra":20,"yearOfEra":2012,"yearOfCentury":12,"weekyear":2012,"monthOfYear":12 *... remainder snipped for brevity*}} …Run Code Online (Sandbox Code Playgroud)