Disaligning a card with integer keys using Jackson
I need to serialize a simple integer map as JSON and then read it back. Serialization is pretty straightforward, however, since the JSON keys must be strings, the resulting JSON looks like this:
{
"123" : "hello",
"456" : "bye",
}
When I read it using the following code:
new ObjectMapper().readValue(json, Map.class)
I get Map<String, String>
instead of Map<Integer, String>
what I need.
I tried to add a key deserializer like this:
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "foo");
map1.put(2, "bar");
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addKeyDeserializer(Integer.class, new KeyDeserializer() {
@Override
public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
System.out.println("deserialize " + key);
return Integer.parseInt(key);
}
});
mapper.registerModule(module);
String json = mapper.writeValueAsString(map1);
Map map2 = mapper.readValue(json, Map.class);
System.out.println(map2);
System.out.println(map2.keySet().iterator().next().getClass());
Unfortunately, my key deserializer never gets called, and map2
in fact Map<String, String>
, so my example prints:
{1=foo, 2=bar}
class java.lang.String
What am I doing wrong and how do I fix this problem?
+3
source to share
1 answer
Using
Map<Integer, String> map2 =
mapper.readValue(json, new TypeReference<Map<Integer, String>>(){});
or
Map<Integer, String> map2 =
mapper.readValue(json, TypeFactory.defaultInstance()
.constructMapType(HashMap.class, Integer.class, String.class));
Your program will output the text below:
deserialize 1
deserialize 2
{1=foo, 2=bar}
class java.lang.Integer
+8
source to share