【发布时间】:2014-12-16 04:53:52
【问题描述】:
我想将一个字符串放入字符串的 ArrayList 中。该字符串基本上是一个 JSONObject,所以我可能只是使用了错误的方法。
字符串的样子是:
String all = "{"users":
[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]}";
我想要的只是 JSONObject 值,所以我的模式给了我这个字符串:
String part = "[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]";
这就是我想要的:
user[0] = "[{"login":"username1"},{"password":"test1"},{"index":"1"}]";
user[1] = "[{"login":"username2"},{"password":"test2"},{"index":"2"}]";
当我尝试将内部 [ ] 之间的所有内容分组时,它只会返回外部 [ ] 中的所有内容。
我试过了:
String[] user = new String[20];
Pattern p = Pattern.compile("(\\[\\{.*\\}\\])");
Matcher m = p.matcher(part);
while(m.find()){
user = m.group().split("\\],\\[");
}
这种方法去掉了我用作分隔符的 ],[。
【问题讨论】:
-
不要尝试使用正则表达式创建一个,只需使用现有的 JSON 或 YAML 库来解析您的
String。 -
使用库处理json:stackoverflow.com/questions/27347763/…