Skip to content

Deserializing non-string map keys with Jackson

I have a a map that looks like this:

public class VerbResult {
    @JsonProperty("similarVerbs")
    private Map<Verb, List<Verb>> similarVerbs;
}

My verb class looks like this:

public class Verb extends Word {
    @JsonCreator
    public Verb(@JsonProperty("start") int start, @JsonProperty("length") int length,
            @JsonProperty("type") String type, @JsonProperty("value") VerbInfo value) {
        super(length, length, type, value);
    }
    //...
}

I want to serialize and deserialize instances of my VerbResult class, but when I do I get this error: Can not find a (Map) Key deserializer for type [simple type, class my.package.Verb]

I read online that you need to tell Jackson how to deserialize map keys, but I didn’t find any information explaining how to go about doing this. The verb class needs to be serialized and deserialzed outside of the map as well, so any solution should preserve this functionality.

Answer

Building on the answer given here that suggests to implement a Module with a deserializer. The JodaTime Module is an easy to understand full example of a module containing serializers and deserializers.

Please note that the Module feature was introduced in Jackson version 1.7 so you might need to upgrade.

So step by step:

  1. create a module containing a (de)serializer for your class based on the Joda example
  2. register that module with mapper.registerModule(module);

and you’ll be all set