我需要将一个简单的整数到字符串的映射序列化为JSON,然后再读取它。序列化很简单,但由于JSON键必须是字符串,因此生成的JSON看起来像:
{
"123" : "hello",
"456" : "bye",
}
当我使用以下代码阅读它时:
new ObjectMapper().readValue(json, Map.class)
我得到了一个 Map<String, String>
,但我需要的是 Map<Integer, String>
。
我尝试添加键解析器,如下所示:
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());
很遗憾我的key deserializer从未被调用,而
map2
实际上是Map<String, String>
,因此我的示例打印出:{1=foo, 2=bar}
class java.lang.String
我做错了什么,如何解决这个问题?