Home >Java >javaTutorial >How to convert between HashMap and String in Java?
When we need to convert HashMap to String in Json format, remember not to use the toString() method of HashMap. You need to use FastJson/Gson to convert HashMap to String. If you use the toString() method for conversion, you cannot convert the string into a HashMap. It will only cause a serialization error:
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);
log:
{key1=value1, key2=value2, key3=value3, key4=value4} {"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
Further execution, visible through Debug:
Convert String to HashMap by converting FastJson to String, but converting toString will report serialization errors.
HashMap toString source code:
HashMap overrides the toString method of the base class. The principle is through a for loop. Connect key and value with = and output. Obviously this is not a Json string format.
JSON.toJSONString(Object object) source code:
FastJson can convert the Object object into a string in Json format through the toJSONString method, and vice versa, you can use Serialization/deserialization method converts Json string into original object.
The above is the detailed content of How to convert between HashMap and String in Java?. For more information, please follow other related articles on the PHP Chinese website!