Deserializing non-string map keys with Jackson

前端 未结 3 1634
说谎
说谎 2020-12-01 14:35

I have a a map that looks like this:

public class VerbResult {
    @JsonProperty(\"similarVerbs\")
    private Map> similarVerbs         


        
3条回答
  •  庸人自扰
    2020-12-01 14:56

    As mentioned above the trick is that you need a key deserializer (this caught me out as well). In my case a non-String map key was configured on my class but it wasn't in the JSON I was parsing so an extremely simple solution worked for me (simply returning null in the key deserializer).

    public class ExampleClassKeyDeserializer extends KeyDeserializer
    {
        @Override
        public Object deserializeKey( final String key,
                                      final DeserializationContext ctxt )
           throws IOException, JsonProcessingException
        {
            return null;
        }
    }
    
    public class ExampleJacksonModule extends SimpleModule
    {
        public ExampleJacksonModule()
        {
            addKeyDeserializer(
                ExampleClass.class,
                new ExampleClassKeyDeserializer() );
        }
    }
    
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule( new ExampleJacksonModule() );
    

提交回复
热议问题