简体   繁体   中英

JSON extract array elements

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");
}

只需尝试:

usernameList = userArray.getJSONObject(i).getString("Username");

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){

    }

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