Java 使用Jackson反序列化具有整数键的map
我必须将一个简单的整数序列化为JSON字符串映射,然后将其读回。 序列化非常简单,但是由于JSON键必须是字符串,因此生成的JSON看起来像:Java 使用Jackson反序列化具有整数键的map,java,jackson,json-deserialization,fasterxml,Java,Jackson,Json Deserialization,Fasterxml,我必须将一个简单的整数序列化为JSON字符串映射,然后将其读回。 序列化非常简单,但是由于JSON键必须是字符串,因此生成的JSON看起来像: { "123" : "hello", "456" : "bye", } 当我使用如下代码阅读时: new ObjectMapper().readValue(json, Map.class) 我得到的是Map,而不是我需要的Map 我尝试添加密钥反序列化器,如下所示: Map<Integer, String> map1 =
{
"123" : "hello",
"456" : "bye",
}
当我使用如下代码阅读时:
new ObjectMapper().readValue(json, Map.class)
我得到的是Map
,而不是我需要的Map
我尝试添加密钥反序列化器,如下所示:
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());
我做错了什么以及如何解决问题?使用
Map<Integer, String> map2 =
mapper.readValue(json, new TypeReference<Map<Integer, String>>(){});
很好,非常感谢。这对我来说无疑是最好的解决办法。然而,我的解决方案不起作用的原因仍然很有趣。Jackson不知道您地图的键和值的类型。需要告诉大家这一点。如果你反序列化到一个POJO,并且POJO有一张地图,那么Jackson似乎知道该怎么做。然而,当直接解析Map时,上面的内容似乎是向Jackson告知itI see的方法。现在很清楚了。非常感谢您的解释。即使我在
mapper.readValue(json,Map.class)的左侧使用map1
代码>那么为什么它不抱怨?map1的键是Integer
,但是当我使用getClass()
时,它被打印为String
。反序列化过程中会发生什么?哈哈,我也有同样的问题。很奇怪你没有更多的选票
Map<Integer, String> map2 =
mapper.readValue(json, new TypeReference<Map<Integer, String>>(){});
Map<Integer, String> map2 =
mapper.readValue(json, TypeFactory.defaultInstance()
.constructMapType(HashMap.class, Integer.class, String.class));
deserialize 1
deserialize 2
{1=foo, 2=bar}
class java.lang.Integer