Wednesday, April 1, 2015

Support for JDK8 types in Spring using Jackson

Spring has introduced RestController to handle rest based services. These controllers help in providing JSON based webservices using Jackson.  A typical REstcontroller based service looks like

@RestController
public class UserRestController{

@RequestMapping(value= "/user/{userId}", method = RequestMethod.GET)
public User getUser(@PathVariable Long userId){
    User user = userService.getUser(userId);
    return user;
  }
}

The default implementation of Jackson handles most of the types. If the user class contains a Java 8 type let's say java.util.Optional than you need to register jackson modules that can handled those types.The jackson modules take care of  serialization/deserialization of these objects.

To register the JDK8 jackson module add the following in your spring dispatcher servlet configuration file

<mvc:annotation-driven>
   <mvc:message-converters>
    <bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
    </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

<bean id="objectMapper"
 class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <property name="modulesToInstall"
value="com.fasterxml.jackson.datatype.jdk8.Jdk8Module" />
</bean>

This is tested in Spring 4.1.5.RELEASE version with jackson as 2.5.1

No comments:

Post a Comment