Home  >  Article  >  Java  >  How to convert between HashMap and String in Java?

How to convert between HashMap and String in Java?

王林
王林forward
2023-04-21 12:52:172994browse

Background:

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:

How to convert between HashMap and String in Java?

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"}

How to convert between HashMap and String in Java?

Further execution, visible through Debug:

How to convert between HashMap and String in Java?

Convert String to HashMap by converting FastJson to String, but converting toString will report serialization errors.

Reason:

HashMap toString source code:

How to convert between HashMap and String in Java?

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:

How to convert between HashMap and String in Java?

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete