我成功使用Spring 3.1 mvc来生成使用json作为http消息的rest webservices。到目前为止,我在我的bean中的每个字段上设置了使用自定义序列化器/反序列化器的符号,并要求jackson以特定格式格式化我的日期。现在我想删除这种表示法语法,并设置一个全局日期格式。这就是我的成就
这是我的servlet配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.test.endpoints" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<bean class="com.test.CustomObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
这是CustomObjectMapper类
package com.test;
import java.text.SimpleDateFormat;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
super();
configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
setDateFormat(new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)"));
}
}
答案 0 :(得分:0)
将以下xml添加到mvc配置以全局覆盖日期序列化。
<mvc:annotation-driven >
<mvc:message-converters register-defaults="false">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="objectMapper">
<bean class="package.CustomObjectMapper"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
并修改CustomObjectMapper类,如下所示。
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper(){
super.configure(Feature.WRITE_DATES_AS_TIMESTAMPS, false);
}
}