Spring 3.1 MVC REST 支持之序列化

来源:互联网 发布:linux下yum下载rpm包 编辑:程序博客网 时间:2024/06/05 20:51

Spring MVC的(JSON)序列化可以通过配置ObjectMapper来实现。为了实现自定义对象或者接口的序列化,我们需要继承ObjectMapper,然后再加入自定义的序列化和反序列化的实现类就可以了。

public class TestObjectMapper extends ObjectMapper {public TestObjectMapper(){super();SimpleModule testModule=new SimpleModule("TestModule", new Version(0,0,1,null));//deserializerstestModule.addDeserializer(IDatetime.class, new DatetimeDeserializer());//serializerstestModule.addSerializer(Date.class, new DateSerializer());registerModule(testModule);//add handler to handler unkonwn object propertygetDeserializationConfig().addHandler(new DeserializationUnknownPropertyHandler());//config to ignore unknown propertyconfigure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);}}
然后再在Spring配置文件中配置:
    <!-- Data Converter -->    <bean id="testObjectMapper" class="com.uv.smp.api.offersearch.v1.util.TestObjectMapper"/><bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="objectMapper" ref="testObjectMapper"/></bean><!-- Method Annotation Mapping -->    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">    <property name="urlDecode" value="true"/>    </bean>    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    <property name="messageConverters">       <list>       <ref bean="jsonConverter" />       </list>   </property>    </bean>     <bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver ">    <property name="messageConverters">       <list>       <ref bean="jsonConverter" />       </list>   </property>    </bean>


原创粉丝点击