Jackson JSON - Deserialize Commons MultiMap

假如想象 提交于 2019-12-01 03:16:58

Being assured from Oxford dictionary that circumvent means to "find a way around (an obstacle)", here is a simple work around.

First I created a method that generate the same MultiValueMap as yours above. And I use the same approach to parse it as a json string.

I then created the following deserialization method

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;


}

Of course this alone falls in the exact issue you mentionned above, therefore I created the doDeserializationAndFormatmethod: it will iterate through each "list inside a list" correponding to a given key and associate one by one the values to the key

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;

}

Here is a simple call in a main method:

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") );

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!