Reputation: 157
I am using Jackson 2.9.6. I have a controller in which I am trying to send an Optional as one of my fields. When I receive a response from the controller I always get it in this format {"field":{"present":true}}
(as shown in this question).
Basically I have a RestTemplate bean configured as such:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
And I would like to add the Jdk8Module as part of the serialzation process. I noticed that there's a MappingJackson2HttpMessageConverter(ObjectMapper mapper)
constructor which takes in an ObjectMapper and I'm thinking of creating an ObjectMapper bean which will have the Jdk8Module registered to it (using a public method called registerModule(Module module)
found in the ObjectMapper class) so I can pass that module as such:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<constructor-arg name="objectMapper" ref="ObjectMapperWithJDK8Bean"></constructor-arg>
</bean>
</list>
</property>
</bean>
<bean id="ObjectMapperWithJDK8Bean" class="com.fasterxml.jackson.databind.ObjectMapper">
* Pass in com.fasterxml.jackson.datatype.jdk8.Jdk8Module here via the method *
</bean>
But the issue im current facing is how to call the registModule
method from the xml file when creating the bean? I am using Spring 4.1. I'm new to Spring so this is pretty challenging!
Upvotes: 3
Views: 8958
Reputation: 6216
You could create a bean with java config instead of xml like :
@Configuration
public class GeneralConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
return mapper;
}
}
I believe that both the @Configuration and @Bean annotations are available since spring 3.0 , so you could use them without any issues. If you still wish to continue with xml based configuration then :
<bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="modulesToInstall"
value="
com.fasterxml.jackson.datatype.jdk8.Jdk8Module,
com.fasterxml.jackson.datatype.jsr310.JavaTimeModule,
com.fasterxml.jackson.module.paramnames.ParameterNamesModule" />
</bean>
Read doc
Upvotes: 5