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

How to convert between HashMap and String in Java?

王林
Release: 2023-04-21 12:52:17
forward
3019 people have browsed it

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);
Copy after login

log:

{key1=value1, key2=value2, key3=value3, key4=value4}
{"key1":"value1","key2":"value2","key3":"value3","key4":"value4"}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template