[英]How to tokenize Java String with nested square brackets?
我有一個要放入字符串ArrayList的字符串。 該字符串基本上是一個JSONObject,所以我可能只是使用了錯誤的方法。
字符串的外觀是:
String all = "{"users":
[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]}";
我想要的只是JSONObject值,因此我的模式給了我這個String:
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("\\],\\[");
}
這種方法擺脫了[],[我將其用作分隔符。
Class User {
private String username;
private String password;
}
Class Users{
LinkedList<User> users;
}
您可以使用任何可用的JSON編組器(例如Jackson等)將字符串反序列化為Users
。
因此,我接受了注釋部分的建議,並確定使用JSON方法足夠了。 我仍然想看看是否有可能用正則表達式來完成。
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.