Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Case insensitive key deserialization for Jackson
import org.codehaus.jackson.map.BeanDescription;
import org.codehaus.jackson.map.BeanProperty;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.KeyDeserializer;
import org.codehaus.jackson.map.KeyDeserializers;
import org.codehaus.jackson.type.JavaType;
import java.io.IOException;
public class CaseInsensitiveKeyDeserializers
implements KeyDeserializers
{
public static final CaseInsensitiveKeyDeserializer DESERIALIZER = new CaseInsensitiveKeyDeserializer();
@Override
public KeyDeserializer findKeyDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc, BeanProperty property)
throws JsonMappingException
{
return DESERIALIZER;
}
private static class CaseInsensitiveKeyDeserializer
extends KeyDeserializer
{
@Override
public Object deserializeKey(String key, DeserializationContext ctxt)
throws IOException
{
return key.toLowerCase();
}
}
}
import org.codehaus.jackson.map.DeserializerProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.deser.StdDeserializerProvider;
import org.testng.annotations.Test;
import java.util.Map;
import static org.testng.Assert.assertEquals;
public class TestCaseInsensitiveKeys
{
@Test
public void testObjectMapper()
throws Exception
{
ObjectMapper objectMapper = new ObjectMapper();
DeserializerProvider provider = new StdDeserializerProvider()
.withAdditionalKeyDeserializers(new CaseInsensitiveKeyDeserializers());
objectMapper.setDeserializerProvider(provider);
Map map = objectMapper.readValue("{\"HELLO\":\"world\"}", Map.class);
assertEquals(map.get("hello"), "world");
}
}
@gongbi

This comment has been minimized.

Copy link

@gongbi gongbi commented Sep 12, 2016

seems this method doesn't work with objectMapper.readTree(...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.