简体   繁体   中英

Java: Convert string representation of array of arrays to an List of Objects

I have this String:

[["username1","name1"],["username2","name2"],["username3","name3"], ...]

And I want to get a List of User objects.

What is a good way to do this?

Thank you.

After many hours of my brain being boiled, I finally found a simple solution:

JSONArray array = new JSONArray(users);

List<UserEntity> userList = new ArrayList<>();

for (int i=0; i<len; i++) {
     JSONArray jsonUser = array.getJSONArray(i);
     UserEntity user = new UserEntity();
     user.setUsername(jsonUser.getString(0));
     user.setName(jsonUser.getString(1));
     userList.add(user);
}

return userList;

users here is the initial string, and len is the length of the array .

User:

Class User {
    String username, name;

    public void setUsername(String username) {
        this.username = username;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public String getName() {
        return name;
    }
}

Convert JSON of 2D array to List:

String json = [["username1","name1"],["username2","name2"],["username3","name3"], ...]
List<User> userList = new ArrayList<>();
JSONArray array = new JSONArray(json);
int count = array.length();
for(int i = 0; i < count; i++) {
    JSONArray innerArray = array.getJSONArray(i);
    User user = new User();
    user.setUsername(innerArray[0]);
    user.setName(innerArray[1]);
    userList.add(user);
}

This isn't a proper format to parse, i don't think it can be parsed with any proper way. The best thing I can suggest you is to break the String again and again with split function at "Bracket([)" and at "Inverted Comas ("")" by creating a logic to get all values one by one!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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