Background:

When we need to convert a HashMap to a String in Json format, remember not to use the toString() method of HashMap. Instead, use FastJson/Gson to convert a HashMap toString. If you use the toString() method for conversion, you cannot convert a string into a HashMap. It only generates serialization errors:

The demo code:

        HashMap<String, String> dataMap = new HashMap<>(4);
        dataMap.put("key1", "value1");
        dataMap.put("key2", "value2");
        dataMap.put("key3", "value3");
        dataMap.put("key4", "value4");
​
        String byToString = dataMap.toString();
        String byJSONString = JSON.toJSONString(dataMap);
        System.out.println(byToString);
        System.out.println(byJSONString);
​
        HashMap<String ,String> hashMap = JSON.parseObject(byJSONString, HashMap.class);
        HashMap<String ,String> hashMap2 = JSON.parseObject(byToString, HashMap.class);
Copy the code

log:

{key1=value1, key2=value2, key3=value3, key4=value4}
{"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
Copy the code

Further down, you can see Debug:

You can convert a String to a HashMap using FastJson to a String, but the toString conversion will report serialization errors.

The reason:

HashMap toString

HashMap overrides the toString method of the base class by concatenating the key and value with = through a for loop, which is clearly not a Json string.

JSON. ToJSONString (Object Object) source:

FastJson converts an Object to a JSON-formatted string using the toJSONString method, or converts a Json string to the original Object by serializing/deserializing it.