0

My JSON data look like this.

{"Users":[
    {"Username":"Admin1", "Password":"123"},
    {"Username":"Admin2", "Password":"456"},
    {"Username":"Admin3", "Password":"789"}
]}

I am trying to extract out all the list of Username and Password.

JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./Database/Users.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray userArray = (JSONArray) jsonObject.get("Users");

How do I then iterate through this JSONArray to achieve what I wanted?

4 Answers 4

3

Sorry if I wasn't clear. I was using org.json.simple, not org.json. And the JSONArray does not have the int length() method.

What I did was

Iterator<JSONObject> iterator = userArray.iterator();
        while (iterator.hasNext()) {
             JSONObject factObj = (JSONObject) iterator.next();
             String userName = (String) factObj.get("Username");
             String passWord = (String) factObj.get("Password");
        }
Sign up to request clarification or add additional context in comments.

Comments

0

Read the javadoc ;)

If you are using org.json.JSONArray, you can loop using int length() to know the array's length and Object get(index) or JSONObject getJSONObject(index) to get an item of the array.

Comments

0

You can iterate with for loop

for (int i = 0; i < userArray.length(); ++i) {
   JSONObject user = recs.getJSONObject(i);
   ...
}

Comments

-1

you can probably do something like the following

for(int i = 0; i < userArray.length; i++) {
   JSONObject user = userArray.getJSONObject(i);
   String username = user.getString("Username");
   String password = user.getString("Password");
   //etc
}

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.