在Java中将String转换为Hashmap

时间:2015-03-18 06:28:34

标签: java regex hashmap

我有以下字符串:

{id=1111, company=A Sample Company}

我想将其转换回hashmap。我尝试了下面的代码

protected HashMap<String,String> convertToStringToHashMap(String text){
    HashMap<String,String> data = new HashMap<String,String>();
    Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
    String[] split = p.split(text);
    for ( int i=1; i+2 <= split.length; i+=2 ){
        data.put( split[i], split[i+1] );
    }
    return data;
}

但问题是它无法使用空格转换字符串。它输出如下内容:

{id=1111, company=A, Sample=Company}

我认为它与正则表达式有关。救命!感谢。

2 个答案:

答案 0 :(得分:1)

这样的事情对你有用:

public static void main(String[] args) {
    String s = "{id=1111, company=A Sample Company}";
    s=s.replaceAll("\\{|\\}", "");
    Map<String, String> hm = new HashMap<String, String>();
    String[] entrySetValues = s.split(",");
    for(String str : entrySetValues){
        String[] arr = str.trim().split("=");
        hm.put(arr[0], arr[1]);
    }
    System.out.println(hm);
}

{id=1111, company=A Sample Company}

答案 1 :(得分:1)

您可以使用Guava&#39;分割器(com.google.common.base.Splitter) https://code.google.com/p/guava-libraries/

String s = "{id=1111, company=A Sample Company}";
String stringWithoutBracket = s.substring(1, s.length() - 1);
Map<String, String> properties = Splitter.on(",").withKeyValueSeparator("=").split(stringWithoutBracket);