title: Custom Deserialization of Generic Types in Jackson Kotlin/Java
body: <p>With this data model...</p>
  
  <p><strong>TestClass.kt</strong></p>
  
  <pre><code>data class TestClass (val bar: Optional&lt;Double&gt;?)
  </code></pre>
  
  <p>My goal is to deserialize the following json values as such:</p>
  
  <pre><code>{"foo": 3.5}  --&gt; foo = 3.5
  {"foo": null} --&gt; foo = Optional.empty() // This is currently my problem. foo is null and I can't seem to fix it
  {}            --&gt; foo = null
  </code></pre>
  
  <p>I've seen the <a href="https://stackoverflow.com/questions/36159677/how-to-create-a-custom-deserializer-in-jackson-for-a-generic-type">solution here</a> and tried this, but the breakpoints in my "deserialize" method never seem to hit.</p>
  
  <p><strong>OptionalDeserializer.java</strong></p>
  
  <pre><code>import com.fasterxml.jackson.core.JsonParser;
  import com.fasterxml.jackson.databind.*;
  import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
  import java.io.IOException;
  import java.util.Optional;
  
  public class OptionalDeserializer extends JsonDeserializer&lt;Optional&lt;?&gt;&gt; implements ContextualDeserializer {
      private JavaType valueType;
  
      @Override
      public JsonDeserializer&lt;?&gt; createContextual(DeserializationContext context, BeanProperty property) {
          this.valueType = property.getType().containedType(0);
          return this;
      }
  
      @Override
      public Optional&lt;?&gt; deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
          final JsonNode node = parser.getCodec().readTree(parser);
  
          return node.isNull()
                  ? Optional.empty()
                  : Optional.of(context.readValue(parser, valueType));
      }
  
  }
  </code></pre>
  
  <p><strong>TestDeserialization.kt</strong></p>
  
  <pre><code>fun main(): {
      val objectMapper = ObjectMapper().registerModule(KotlinModule())
  
      val module = SimpleModule()
      module.addDeserializer(Optional::class.java, OptionalDeserializer())
      objectMapper.registerModule(module)
  
      objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
  
      objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
      objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
      objectMapper.nodeFactory = JsonNodeFactory.withExactBigDecimals(true)
  
      val inputJson = """{"foo" : null}"""
  
      val expectedObject = TestClass(foo = Optional.empty())
  
      val actualObject = objectMapper.readValue(inputJson, TestClassBravo::class.java)
  
      assertEquals(expectedObject, actualObject)
  }
  </code></pre>
  
  <p><strong>build.gradle (for version info)</strong></p>
  
  <pre><code>compile 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
  compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8'
  </code></pre>