字符串格式是(不是json格式):
a="0PN5J17HBGZHT7JJ3X82", b="frJIUN8DYpKDtOLCwo/yzg="
我想将此字符串转换为HashMap:
键a
,其值为0PN5J17HBGZHT7JJ3X82
键b
,其值为frJIUN8DYpKDtOLCwo/yzg=
有方便的方法吗?感谢
我尝试了什么:
Map<String, String> map = new HashMap<String, String>();
String s = "a=\"00PN5J17HBGZHT7JJ3X82\",b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String []tmp = StringUtils.split(s,',');
for (String v : tmp) {
String[] t = StringUtils.split(v,'=');
map.put(t[0], t[1]);
}
我得到了这个结果:
键a
,其值为"0PN5J17HBGZHT7JJ3X82"
键b
,其值为"frJIUN8DYpKDtOLCwo/yzg
对于键a
,开头和结尾双引号(“)是不需要的;对于键b
,开始双引号(”)是不需要的,最后一个等号(=)不见了。
抱歉我的英语很差。
答案 0 :(得分:7)
可能你并不关心它是一个HashMap,只是一个Map,所以这样做,因为Properties实现了Map:
import java.io.StringReader;
import java.util.*;
public class Strings {
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
System.out.println(properties);
}
}
输出:
{b="frJIUN8DYpKDtOLCwo/yzg=", a="0PN5J17HBGZHT7JJ3X82"}
如果您绝对需要HashMap,可以使用Properties对象作为输入构建一个:new HashMap(properties)
。
答案 1 :(得分:1)
在commas (",")
的基础上拆分字符串,然后用("=")
String s = "Comma Separated String";
HashMap<String, String> map = new HashMap<String, String>();
String[] arr = s.split(",");
String[] arStr = arr.split("=");
map.put(arr[0], arr[1]);
答案 2 :(得分:1)
在Ryan的代码中添加了一些更改
public static void main(String[] args) throws Exception {
String input = "a=\"0PN5J17HBGZHT7JJ3X82\", b=\"frJIUN8DYpKDtOLCwo/yzg=\"";
input=input.replaceAll("\"", "");
String propertiesFormat = input.replaceAll(",", "\n");
Properties properties = new Properties();
properties.load(new StringReader(propertiesFormat));
Set<Entry<Object, Object>> entrySet = properties.entrySet();
HashMap<String,String > map = new HashMap<String, String>();
for (Iterator<Entry<Object, Object>> it = entrySet.iterator(); it.hasNext();) {
Entry<Object,Object> entry = it.next();
map.put((String)entry.getKey(), (String)entry.getValue());
}
System.out.println(map);
}
答案 3 :(得分:0)
您也可以使用以下正则表达式。
Map<String,String> data = new HashMap<String,String>();
Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
String[] split = p.split(text);
for ( int i=0; i+2 <= split.length; i+=2 ){
data.put( split[i], split[i+1] );
}
return data;