简体   繁体   English

如何用嵌套方括号标记Java字符串?

[英]How to tokenize Java String with nested square brackets?

I have a string I would like to put into an ArrayList of Strings. 我有一个要放入字符串ArrayList的字符串。 The string is basically a JSONObject so I might just be using the wrong methods. 该字符串基本上是一个JSONObject,所以我可能只是使用了错误的方法。

The way the string looks is: 字符串的外观是:

String all = "{"users":
[
 [{"login":"username1"},{"password":"test1"},{"index":"1"}],
 [{"login":"username2"},{"password":"test2"},{"index":"2"}]
]}";

All I want is the JSONObject values so my pattern gives me this String: 我想要的只是JSONObject值,因此我的模式给了我这个String:

String part = "[
                [{"login":"username1"},{"password":"test1"},{"index":"1"}],
                [{"login":"username2"},{"password":"test2"},{"index":"2"}]
               ]";

This is what I want: 这就是我要的:

user[0] = "[{"login":"username1"},{"password":"test1"},{"index":"1"}]";
user[1] = "[{"login":"username2"},{"password":"test2"},{"index":"2"}]";

When I try to group everything in between the inner [ ] it just returns everything in the outer [ ]. 当我尝试将内部[]之间的所有内容分组时,它只返回外部[]中的所有内容。

I have tried: 我努力了:

String[] user = new String[20];
Pattern p = Pattern.compile("(\\[\\{.*\\}\\])");
Matcher m = p.matcher(part);
while(m.find()){
    user = m.group().split("\\],\\[");
}

This approach gets rid of the ],[ which I'm using as a delimiter. 这种方法摆脱了[],[我将其用作分隔符。

Class User {
  private String username;
  private String password;
}

Class Users{
  LinkedList<User> users;
}

You can use any available JSON marshallers like Jackson etc to deserialize the string into a Users . 您可以使用任何可用的JSON编组器(例如Jackson等)将字符串反序列化为Users

So I took the advice from the comment section and sure enough using JSON methods was the way to go. 因此,我接受了注释部分的建议,并确定使用JSON方法足够了。 I would still like to see if it was possible to accomplish with regular expressions. 我仍然想看看是否有可能用正则表达式来完成。

ArrayList<String> myList = new ArrayList<String>();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();

obj = {"user":"[[{},{},{}],[{},{},{}]]";

// This gives me the outer JSONArray    
arr = obj.getJSONArray("user");

// This iterates through the outer JSONArray assigning each inner JSONArray
// to my ArrayList as strings.
for( int i = 0; i < arr.length(); i++){
    myList.put(arr.getJSONArray(i).toString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM