62,635
社区成员




Map test = new HashMap();
test.put("a", "1");
test.put("b", "2");
test.put("c", "3");
String testStr = test.toString();
System.out.println(testStr);
String jsonStr = testStr.replaceAll("([^,\\{\\s]*)=([^,\\]\\}]*)", "\"$1\":\"$2\"");
System.out.println(jsonStr);
System.out.println(new ObjectMapper().readValue(jsonStr, HashMap.class));
//JsonMap实现
public static class JsonMap<K, V> extends HashMap<K, V> {
private static final long serialVersionUID = -4083915643878380063L;
//从Json构造Map
public static <K,V> JsonMap<K, V> fromJson(String json){
@SuppressWarnings("unchecked")
JsonMap<K, V> map = JSON.parseObject(json, JsonMap.class);
return map;
}
//重写toString方法
@Override
public String toString(){
return JSON.toJSONString(this);
}
}
//测试
public static void main(String[] args) {
JsonMap<String, String> jmap = new JsonMap<String, String>();
jmap.put("hello", "world");
jmap.put("你好", "世界");
String jmapString = jmap.toString();
System.out.println(jmap); //此处会自动调用toString()
jmap = JsonMap.fromJson(jmapString);
System.out.println(jmap.get("hello"));
}
这样,只需要把程序里需要恢复现场的HashMap改成JsonMap,然后修改恢复逻辑即可。
当然,你也可以将toString于fromJson方法包装到一个工具类中,这个就需要你根据具体的业务环境进行取舍了。