Which approach correctly reads and uses this JSON data in Java to loop through each user?
hard
A. JSONObject users = obj.getJSONObject("users");
for (int i = 0; i < users.length(); i++) {
String username = users.getString("username");
String password = users.getString("password");
}
B. JSONArray users = obj.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String username = user.getString("username");
String password = user.getString("password");
// use username and password
}
C. String users = obj.getString("users");
for (String user : users) {
// use user
}
D. JSONArray users = obj.getJSONArray("users");
for (int i = 0; i <= users.length(); i++) {
JSONObject user = users.getJSONObject(i);
// use user
}
Solution
Step 1: Identify JSON array access
The key "users" holds a JSON array, so getJSONArray("users") is correct.
Step 2: Loop correctly over array
Loop from 0 to users.length() - 1, get each JSONObject, then extract username and password.
Step 3: Check options
JSONArray users = obj.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String username = user.getString("username");
String password = user.getString("password");
// use username and password
} correctly uses JSONArray, loops with i < length, and extracts data properly.
Final Answer:
JSONArray users = obj.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
JSONObject user = users.getJSONObject(i);
String username = user.getString("username");
String password = user.getString("password");
// use username and password
} -> Option B
Quick Check:
JSONArray + for loop with i < length = A [OK]
Hint: Use JSONArray and loop i < length, not <= [OK]
Common Mistakes:
Using getJSONObject instead of getJSONArray for array
Looping with i <= length causing IndexOutOfBounds
Treating JSON array as string
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.