我正在使用
Spring MVC 3.0.5和Jackson 1.7.2.
我希望实现一个Dynamic Bean序列化器赋值机制,例如,假设我的MVC Controller返回(@ResponseBody)一个MyObject类型的Object.默认情况下,Jackson的SerializerFactory将寻找最合适的Serializer,包括我的自定义Serializers(例如CustomSerializer扩展JsonSerializer< MyObject>).
但是,我希望在某些标志处于活动状态时触发我的自定义序列化程序(假设一个布尔变量附加到ThreadLocal).否则,我想使用Jackson提供的Serializers,保持MappingJacksonHttpMessageConverter的默认行为不变.
有没有办法实现这个方法?
我已经在Spring的< mvc:annotaion-driven />中注册了我自己的ObjectMapper,SerializerFactory和CustomSerializers.默认MappingJacksonHttpMessageConverter.
public class ConvertingPostProcessor implements BeanPostProcessor {
private ObjectMapper jacksonJsonObjectMapper;
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
if (bean instanceof AnnotationMethodHandlerAdapter) {
HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
for (HttpMessageConverter<?> conv: convs) {
if (conv instanceof MappingJacksonHttpMessageConverter) {
((MappingJacksonHttpMessageConverter) conv).setObjectMapper(jacksonJsonObjectMapper);
}
}
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
return bean;
}
public void setJacksonJsonObjectMapper(ObjectMapper jacksonJsonObjectMapper) {
this.jacksonJsonObjectMapper = jacksonJsonObjectMapper;
}
}
而spring-mvc.xml将是:
<mvc:annotation-driven />
...
<bean id="jacksonJsonObjectMapper" class="org.mycode.serialize.CustomObjectMapper">
<property name="customSerializerFactory" ref="jacksonJsonCustomSerializerFactory" />
</bean>
<bean id="jacksonJsonCustomSerializerFactory" class="org.mycode.serialize.CustomSerializerFactoryRegistry">
<property name="serializers">
<map>
<entry key="org.mycode.domain.MyObject" value-ref="customSerializer" />
</map>
</property>
</bean>
<bean id="customSerializer" class="org.mycode.serialize.CustomSerializer">
<property name="jacksonJsonCustomSerializerFactory" ref="jacksonJsonCustomSerializerFactory" />
</bean>
<bean id="convertingPostProcessor" class="org.mycode.serialize.ConvertingPostProcessor">
<property name="jacksonJsonObjectMapper" ref="jacksonJsonObjectMapper" />
</bean>
提前致谢!!
最佳答案 杰克逊库现在还不够成熟.所以渲染模型对象有问题.它提供了一些注释和过滤器来自定义渲染的json但是还不够.所以我建议你只使用
dozer为视图创建新的java类并将域对象映射到这个视图类framework end在responsebody中返回此视图类.