jacksonJSON – 反编译Commons MultiMap
我想使用JSON序列化和反序列化MultiMap(Apache Commons 4)。
要测试的代码段:
MultiMap map = new MultiValueMap(); map.put("Key 1", "Val 11"); map.put("Key 1", "Val 12"); map.put("Key 2", "Val 21"); map.put("Key 2", "Val 22"); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(map); MultiMap deserializedMap = mapper.readValue(jsonString, MultiValueMap.class);
序列化工作正常,并产生我期望的格式:
{"Key 1":["Val 11","Val 12"],"Key 2":["Val 21","Val 22"]}
不幸的是,反序列化产生的结果不是它看起来的样子:在反序列化之后,Multimap在ArrayList中包含一个用于键值的ArrayList,而不是包含值的键的单个ArrayList。
由于MultiMap实现了Map接口,因此调用多映射的put()
方法来添加在json字符串中找到的数组,从而产生了这个结果。
如果将新值放入非现有键,MultiMap实现本身将再次创建一个ArrayList。
有没有办法绕过这个?
感谢您的帮助!
从牛津词典中得到保证,绕过“寻找方法(障碍)”的方法,这是一个简单的解决方法。
首先,我创建了一个生成与上面相同的MultiValueMap的方法。 我使用相同的方法将其解析为json字符串。
然后我创建了以下反序列化方法
public static MultiMap doDeserialization(String serializedString) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); Class classz = MultiValueMap.class; MultiMap map = mapper.readValue(serializedString, classz); return (MultiMap) map; }
当然,这仅仅是你上面提到的确切问题,因此我创建了doDeserializationAndFormat
方法:它将遍历每个“列表中的列表”,对应于给定的键并将值逐个关联到键
public static MultiMap doDeserializationAndFormat(String serializedString) throws JsonParseException, JsonMappingException, IOException { MultiMap source = doDeserialization(serializedString); MultiMap result = new MultiValueMap(); for (String key: source.keySet()) { List allValues = (List)source.get(key); Iterator iter = allValues.iterator(); while (iter.hasNext()) { List datas = (List )iter.next(); for (String s: datas) { result.put(key, s); } } } return result; }
这是一个主要方法中的简单调用:
MultiValueMap userParsedMap = (MultiValueMap)doDeserializationAndFormat(stackMapSerialized); System.out.println("Key 1 = " + userParsedMap.get("Key 1") ); System.out.println("Key 2 = " + userParsedMap.get("Key 2") );
希望这可以帮助。