6

我必须将一个简单的整数到字符串映射序列化为 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 deserialzier 从未被调用,map2实际上是Map<String, String>,所以我的示例打印:

{1=foo, 2=bar}
class java.lang.String

我做错了什么以及如何解决问题?

4

1 回答 1

13

Use

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 below text:

deserialize 1
deserialize 2
{1=foo, 2=bar}
class java.lang.Integer
于 2015-07-05T13:59:27.827 回答