0

I have this JSON file right now:

{
    "0": {
        "username": "username1",
        "password": "password1"
    },
    "1": {
        "username": "username2",
        "password": "password2"
    }
}

I want to get all of the usernames and convert it into a ArrayList. So my ArrayList will have just the usernames, username1, and username2.

I'm using org.JSON also.

  • That's a bit vague. Usually json representation in Java work like a HashMap read the docs and learn to code to be a bit harsh... – meow Jan 06 '18 at 16:32
  • Possible duplicate of [Parsing JSON string in Java](https://stackoverflow.com/questions/11874919/parsing-json-string-in-java) – Ravi Jan 07 '18 at 15:00

1 Answers1

0

Assume you have read your file to jsonString.

JSONObject json = new JSONObject(jsonString);
List<String> usernames = new ArrayList<>();
for (int i = 0; i < json.length(); i++) {
    JSONObject user = json.getJSONObject(i + "");
    usernames.add(user.getString("username"));
}
zhh
  • 2,346
  • 1
  • 11
  • 22