Created
October 3, 2011 22:59
-
-
Save electrum/1260489 to your computer and use it in GitHub Desktop.
Case insensitive key deserialization for Jackson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seems this method doesn't work with objectMapper.readTree(...