【发布时间】:2012-11-21 22:59:18
【问题描述】:
我正在使用 Spring MVC 3.2RC1 中的 REST API。
我正在获取一个带有 org.joda.time.DateTime 时间戳的 JPA 实体,并让 Spring 使用
将其序列化为 JSON@RequestMapping(value = "/foobar", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
在 Spring 中使用默认的 Jackson2 设置,因为我只添加了
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.1</version>
</dependency>
到我的 POM 并让 Spring 自行连接。
控制器正在生成:
"created":{"year":2012,"dayOfMonth":30,"dayOfWeek":5,"era":1,"dayOfYear":335,"weekOfWeekyear":48,"weekyear":2012,"monthOfYear":11,"yearOfEra":2012,"yearOfCentury":12,"centuryOfEra":20,"millisOfSecond":39,"millisOfDay":52684039,"secondOfMinute":4,"secondOfDay":52684,"minuteOfHour":38,"minuteOfDay":878,"hourOfDay":14,"millis":1354282684039,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Stockholm"},"fixed":false,"id":"Europe/Stockholm"},"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Stockholm"},"fixed":false,"id":"Europe/Stockholm"}},"afterNow":false,"beforeNow":true,"equalNow":false}
但我希望它是 ISO8601 日期,例如 2007-11-16T20:14:06.3Z(或带有偏移量)。
我的猜测是我需要访问 ObjectMapper 并设置 mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);但是在使用时如何访问 ObjectMapper
<mvc:annotation-driven />
附:我使用 UserType 使用 JPA/Hibernate4 将对象持久化到 PostgreSQL 以获得 JodaTime 支持。 D.S.
更新
下面的配置解决了 java.util.Date 的问题,但 JodaTime 仍然没有骰子。
<annotation-driven>
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper">
<beans:bean
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ">
</beans:bean>
</beans:property>
</beans:bean>
</message-converters>
</annotation-driven>
【问题讨论】:
-
不,不是。我放弃了 Joda 时间类型,并在我的 DTO 中使用了常规日期。如果你没记错的话,请添加
在 Jackson2ObjectMapperFactoryBean bean 中,您将其作为纪元时间戳获取,并且 joda jackson 模块需要补丁才能使用 simpleDateFormat。: array>
标签: json spring spring-mvc jackson jodatime