In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to solve the problem of string conversion between HashMap and String in Java. I hope you will get something after reading this article. Let's discuss it together.
Background:
When we have a need to convert HashMap to String in Json format, remember not to use the toString () method of HashMap, but to use FastJson/Gson to convert HashMap to String. If you use the toString () method for conversion, you cannot convert the string back to HashMap. It will only have serialization errors:
Demo Code:
HashMap 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 hashMap = JSON.parseObject (byJSONString, HashMap.class); HashMap hashMap2 = JSON.parseObject (byToString, HashMap.class)
Log:
{key1=value1, key2=value2, key3=value3, key4=value4} {"key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"}
If you execute further, you can see through Debug:
String can be converted to HashMap by converting FastJson to String, but serialization problems will be reported by toString conversion.
Reason:
HashMap toString source code:
HashMap overrides the toString method of the base class, which is output after connecting key and value with = through a for loop, which is obviously not a Json string format.
JSON.toJSONString (Object object) source code:
FastJson can convert the Object object to a string in Json format through the toJSONString method, while the Json string can be converted to the original object by serialization / deserialization.
After reading this article, I believe you have a certain understanding of "how to solve the problem of string conversion between HashMap and String in Java". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.