How to convert String into Hashmap in java

后端 未结 6 778
梦如初夏
梦如初夏 2020-12-15 04:43

How can I convert a String into a HashMap?

String value = \"{first_name = naresh, last_nam         


        
6条回答
  •  攒了一身酷
    2020-12-15 05:12

    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 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.

提交回复
热议问题