Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Rest Controller handling java.util.Optional using Jackson

I have got Spring RestController classes to handle rest services using JSON. For JSON I am using Jackson. There are fields of java.util.Optional type

 private Optional<Long> start = Optional.empty();

To enable the handling of Optional type, I am configuring the Spring as follows

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

However when I call the webservice, it fails in deserializing the Optional types with following message

org.springframework.http.converter.HttpMessageNotReadableException: 
   Could not read JSON: Can not instantiate value of type 
   [simple type, class java.util.Optional<java.lang.Long>] 
   from Long integral number (3424323423432); no 
   single-long-arg constructor/factory method

Doing serialization/deserialization from stand alone code works fine. There I register the module directly using the following code

    ObjectMapper m = new ObjectMapper();
    m.registerModule(new Jdk8Module());

Versions I am using:

Spring : 4.1.5.RELEASE

Jackson: 2.5.1

Thanks in advance

like image 633
lalit Avatar asked Apr 01 '15 08:04

lalit


1 Answers

I could figure out this. The solution is to register the object mapper to Message converter as follows

<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>
like image 66
lalit Avatar answered Oct 13 '22 01:10

lalit