Reputation: 51
I'm using Spring MVC 3.0.5 with Jackson 1.7.2.
I wish to implement a Dynamic Bean serializer assignment mechanism, for example, let's say that my MVC Controller returns (@ResponseBody
) an Object of type MyObject. By default, Jackson's SerializerFactory will look for the most appropriate Serializer, including my custom Serializers (like for example CustomSerializer extends JsonSerializer<MyObject>
).
However, I want my custom Serializers to be triggered just in case some flag is active (let's say, a boolean variable attached to ThreadLocal). Otherwise, I want to use Jackson provided Serializers, keeping MappingJacksonHttpMessageConverter
's default behaviour intact.
Is there any way to implement an approach to that?
I've already registered my own ObjectMapper, SerializerFactory and CustomSerializers into Spring's <mvc:annotaion-driven />
default 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;
}
}
And spring-mvc.xml would be:
<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>
Thanks in advance!!
Upvotes: 5
Views: 4828
Reputation: 1596
Jackson library not enough mature for now.So rendering model object problematic.It provide a few annotation and filter to customize rendered json but not enough.So i suggest you create new java classes for just views and map domain objects to this view class using dozer framework end return this view classes in responsebody.
Upvotes: 2