title: Jackson Modules for Map Serialization
body: <p>I have a Class that contains a Map (with non String key) and some other fields.</p>
  
  <pre><code>public class MyClass() {
      private Map&lt;KeyObject, OtherObject&gt; map;
      private String someField;
  
      public MyClass(Map&lt;KeyObject, OtherObject&gt; map, String someField) {
          this.map = map;
          this.someField = someField;
      }
  
      // Getters &amp; Setters
  }
  </code></pre>
  
  <p>I would like to serialize and deserialize this class using Jackson.
  I saw a different ways of doing that and decided to try using <a href="http://wiki.fasterxml.com/JacksonFeatureModules" rel="noreferrer">jackson modules</a>.</p>
  
  <p>I followed <a href="http://dev.sghill.net/2012/04/how-do-i-write-jackson-json-serializer.html" rel="noreferrer">this post</a> and extended JsonDeserializer and JsonSerializer. The problem is that those classes should be typed, so it should look like</p>
  
  <pre><code>public class keyDeserializer extends JsonDeserializer&lt;Map&lt;KeyObject, OtherObject&gt;&gt; {
  ...
  }
  </code></pre>
  
  <p>The same for the KeySerializer.</p>
  
  <p>Then adding to the module:</p>
  
  <pre><code>module.addSerializer(new keySerializer());
  module.addDeserializer(Map.class, new keyDeserializer());
  </code></pre>
  
  <p>But this is wrong apparently since I'm getting an exception:</p>
  
  <pre><code>keySerializer does not define valid handledType() -- must either register with method that takes type argument  or make serializer extend 'org.codehaus.jackson.map.ser.std.SerializerBase'
  </code></pre>
  
  <p>I could have my serializer and deserializer to be typed to <strong>MyClass</strong>, but then I had to manually parse all of it, which is not reasonable.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I managed to bypass the module creation in the code by using annotations</p>
  
  <pre><code>@JsonDeserialize(using = keyDeserializer.class)
  @JsonSerialize(using = keySerializer.class)
  private Map&lt;KeyObject, OtherObject&gt; map;
  </code></pre>
  
  <p>But then I have to serialize/deserialize the whole map structure on my own from the toString() output. So tried a different annotation:</p>
  
  <pre><code>@JsonDeserialize(keyUsing = MyKeyDeserializer.class)
  private Map&lt;KeyObject, OtherObject&gt; map;
  </code></pre>
  
  <p>Where MyKeyDeserializer extends <code>org.codehaus.jackson.map.KeyDeserializer</code> and overriding the method</p>
  
  <pre><code>public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {...}
  </code></pre>
  
  <p>Then manually deserializing my key but again from the toString() output of my key class.</p>
  
  <p>This is not optimal (this dependency on the toString() method). Is there a better way?</p>