字符串格式是(不是json格式):
a="0PN5J17HBGZHT7JJ3X82", b="frJIUN8DYpKDtOLCwo/yzg="
Run Code Online (Sandbox Code Playgroud)
我想将此字符串转换为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]);
}
Run Code Online (Sandbox Code Playgroud)
我得到这个结果:
a有价值的关键"0PN5J17HBGZHT7JJ3X82"
b有价值的关键"frJIUN8DYpKDtOLCwo/yzg
对于键a,开始和结束双引号(")是不需要的;对于键b,开始双引号(")是不需要的,并且最后一个等号(=)丢失.抱歉我的英语不好.
可能你并不关心它是一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{b="frJIUN8DYpKDtOLCwo/yzg=", a="0PN5J17HBGZHT7JJ3X82"}
Run Code Online (Sandbox Code Playgroud)
如果您绝对需要HashMap,可以使用Properties对象构造一个作为输入:new HashMap(properties).
| 归档时间: |
|
| 查看次数: |
13018 次 |
| 最近记录: |