How to convert String into Hashmap in java
You can do it in single line, for any object type not just Map.
(Since I use Gson quite liberally, I am sharing a Gson based approach)
Gson gson = new Gson();
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);
What it does is:
gson.toJson(value)
will serialize your object into its equivalent Json representation.gson.fromJson
will convert the Json string to specified object. (in this example -Map
)
There are 2 advantages with this approach:
- The flexibility to pass an Object instead of String to
toJson
method. - You can use this single line to convert to any object even your own declared objects.
This is one solution. If you want to make it more generic, you can use the StringUtils
library.
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils
which is contained in apache.commons.lang
package.