1

I have a string I would like to put into an ArrayList of Strings. The string is basically a JSONObject so I might just be using the wrong methods.

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:

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.

Kasper-34
  • 47
  • 9

2 Answers2

0
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.

abhati
  • 309
  • 1
  • 6
0

So I took the advice from the comment section and sure enough using JSON methods was the way to go. 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());
}
Kasper-34
  • 47
  • 9