Jackson JSON - 反序列化 Commons MultiMap

Jackson JSON - Deserialize Commons MultiMap

我想使用 JSON.

序列化和反序列化 MultiMap (Apache Commons 4)

要测试的代码:

MultiMap<String, String> 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<String, String> deserializedMap = mapper.readValue(jsonString, MultiValueMap.class);

序列化工作正常,结果格式符合我的预期:

{"Key 1":["Val 11","Val 12"],"Key 2":["Val 21","Val 22"]}

不幸的是,反序列化产生的结果不是它应该看起来的样子: 反序列化后,Multimap 在 ArrayList 中包含一个 ArrayList 作为键的值,而不是包含值的键的单个 ArrayList。

这个结果是由于MultiMap实现了Map接口,调用了multi map的put()方法添加json字符串中的数组。

如果将新值放入不存在的键中,MultiMap 实现本身会再次创建一个 ArrayList。

有什么办法可以避免这种情况吗?

感谢您的帮助!

根据牛津词典确定规避的意思是 "find a way around (an obstacle)",这里有一个简单的解决方法。

首先,我创建了一个生成与上面相同的 MultiValueMap 的方法。我使用相同的方法将其解析为 json 字符串。

然后我创建了以下反序列化方法

public static MultiMap<String,String> doDeserialization(String serializedString) throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    Class<MultiValueMap> classz = MultiValueMap.class;
    MultiMap map = mapper.readValue(serializedString, classz);
    return (MultiMap<String, String>) map;


}

当然,这本身就属于您上面提到的确切问题,因此我创建了 doDeserializationAndFormat 方法:它将遍历每个 "list inside a list" 对应于给定键并逐一关联键的值

public static MultiMap<String, String> doDeserializationAndFormat(String serializedString) throws JsonParseException, JsonMappingException, IOException {
    MultiMap<String, String> source = doDeserialization(serializedString);
    MultiMap<String, String> result  =  new MultiValueMap<String,String>();
    for (String key: source.keySet()) {


        List allValues = (List)source.get(key);
        Iterator iter = allValues.iterator();

        while (iter.hasNext()) {
            List<String> datas = (List<String>)iter.next();

            for (String s: datas) {
                result.put(key, s);
            }
        }

    }

    return result;

}

下面是 main 方法中的一个简单调用:

MultiValueMap<String,String> userParsedMap = (MultiValueMap)doDeserializationAndFormat(stackMapSerialized);
System.out.println("Key 1 = " + userParsedMap.get("Key 1") );
System.out.println("Key 2 = " + userParsedMap.get("Key 2") );

希望对您有所帮助。