1

Given the following JSON

{  
   "Users":[  
      {  
         "Username":"John",
         "Password":"Doe"
      },
      {  
         "Username":"Anna",
         "Password":"Smith"
      },
      {  
         "Username":"Peter",
         "Password":"Jones"
      }
   ]
}

I am trying to extract an array list of UserName & Password

JSONObject jobj = new JSONObject(jsonData);
JSONArray userArray = jobj.getJSONArray("Users"); // Now I got the Array of Users

I need to do something to extract all the user and password. What function is there for this? I am using the org JSON library

for (int i=0;i<userArray.length();i++)
{
    // something like that
    usernameList = userArray[i].getData("Username");
    passwordList = userArray[i].getData("Password");
}

2 Answers 2

1

Just try with:

usernameList = userArray.getJSONObject(i).getString("Username");
Sign up to request clarification or add additional context in comments.

Comments

1

to get a List of all userNames and Password you need to iterate through all the elements in the array and then add individual userNames and passwords to the lists.

Something Like this:

    List<String> userList = new ArrayList<>();
    List<String> passwordList = new ArrayList<>();

    try {
        for (int i = 0; i < userArray.length(); i++) {
            JSONObject user = userArray.getJSONObject(i);
            userList.add(user.getString("Username"));
            passwordList.add(user.getString("Password"));
        }
    }catch(Exception e){

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.