简体   繁体   English

JSON提取数组元素

[英]JSON extract array elements

Given the following JSON 给定以下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 我正在尝试提取UserNamePassword的数组列表

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 我正在使用组织JSON库

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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