Convert HashMap.toString() back to HashMap in Java

后端 未结 12 1695
执念已碎
执念已碎 2020-12-14 00:35

I put a key-value pair in a Java HashMap and converted it to a String using the toString() method.

Is it possible to convert t

12条回答
  •  轮回少年
    2020-12-14 00:56

    you cannot do this directly but i did this in a crazy way as below...

    The basic idea is that, 1st you need to convert HashMap String into Json then you can deserialize Json using Gson/Genson etc into HashMap again.

    @SuppressWarnings("unchecked")
    private HashMap toHashMap(String s) {
        HashMap map = null;
        try {
            map = new Genson().deserialize(toJson(s), HashMap.class);
        } catch (TransformationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    private String toJson(String s) {
        s = s.substring(0, s.length()).replace("{", "{\"");
        s = s.substring(0, s.length()).replace("}", "\"}");
        s = s.substring(0, s.length()).replace(", ", "\", \"");
        s = s.substring(0, s.length()).replace("=", "\":\"");
        s = s.substring(0, s.length()).replace("\"[", "[");
        s = s.substring(0, s.length()).replace("]\"", "]");
        s = s.substring(0, s.length()).replace("}\", \"{", "}, {");
        return s;
    }
    

    implementation...

    HashMap map = new HashMap();
    map.put("Name", "Suleman");
    map.put("Country", "Pakistan");
    String s = map.toString();
    HashMap newMap = toHashMap(s);
    System.out.println(newMap);
    

提交回复
热议问题