JSON
Android
Java
Array Iteration
Mobile Development

JSON Array iteration in Android/Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Iterating through a JSON array in Android or Java is straightforward once you know the shape of the payload. The core pattern is to parse the JSONArray, loop from 0 to length() - 1, and read each element safely, but production code also needs null handling, optional fields, and Android threading concerns.

Basic JSONArray Iteration

Using org.json, the standard pattern looks like this:

java
1import org.json.JSONArray;
2import org.json.JSONObject;
3
4String response = "[{\"id\":1,\"name\":\"Ana\"},{\"id\":2,\"name\":\"Ben\"}]";
5JSONArray array = new JSONArray(response);
6
7for (int i = 0; i < array.length(); i++) {
8    JSONObject item = array.getJSONObject(i);
9    int id = item.optInt("id", -1);
10    String name = item.optString("name", "unknown");
11
12    System.out.println(id + " " + name);
13}

That covers the core mechanics:

  • parse the text into a JSONArray
  • access each element by index
  • cast each element to a JSONObject
  • read fields from that object

This is usually the right starting point when you know the JSON is an array of objects.

Prefer opt* Methods for Defensive Parsing

One of the easiest ways to make JSON parsing brittle is to call getString() and getInt() on every field as if the payload will never change.

Safer methods include:

  • 'optString'
  • 'optInt'
  • 'optBoolean'
  • 'optJSONArray'
  • 'optJSONObject'

Example:

java
String title = item.optString("title", "untitled");
int count = item.optInt("count", 0);
boolean enabled = item.optBoolean("enabled", false);

These methods are useful when:

  • a field is optional
  • an API occasionally omits properties
  • you want default values instead of exceptions

Use the stricter get* methods only when a missing field really should fail the whole parse.

Nested Arrays Need Explicit Inner Loops

Real payloads often contain arrays inside objects:

java
1import org.json.JSONArray;
2import org.json.JSONObject;
3
4String response = "[{\"name\":\"Ana\",\"tags\":[\"admin\",\"mobile\"]}]";
5JSONArray users = new JSONArray(response);
6
7for (int i = 0; i < users.length(); i++) {
8    JSONObject user = users.getJSONObject(i);
9    JSONArray tags = user.optJSONArray("tags");
10
11    if (tags == null) {
12        continue;
13    }
14
15    for (int j = 0; j < tags.length(); j++) {
16        System.out.println(user.optString("name") + ": " + tags.optString(j));
17    }
18}

The structure is the same as the outer loop. You just step into the nested JSONArray and iterate it the same way.

Convert JSON to Model Objects

Often the loop should not directly update UI or business logic. A cleaner pattern is to map each JSON object into a Java model:

java
1import java.util.ArrayList;
2import java.util.List;
3import org.json.JSONArray;
4import org.json.JSONObject;
5
6class User {
7    final int id;
8    final String name;
9
10    User(int id, String name) {
11        this.id = id;
12        this.name = name;
13    }
14}
15
16List<User> parseUsers(String response) throws Exception {
17    JSONArray array = new JSONArray(response);
18    List<User> users = new ArrayList<>();
19
20    for (int i = 0; i < array.length(); i++) {
21        JSONObject item = array.getJSONObject(i);
22        users.add(new User(
23            item.optInt("id", -1),
24            item.optString("name", "unknown")
25        ));
26    }
27
28    return users;
29}

That keeps parsing separate from display logic and makes the code easier to test.

Do Not Parse Large Payloads on the Main Thread

In Android, heavy parsing should not run on the UI thread. Large arrays can make the app stutter or even trigger application-not-responding behavior.

A simple executor-based approach:

java
1ExecutorService executor = Executors.newSingleThreadExecutor();
2Handler mainHandler = new Handler(Looper.getMainLooper());
3
4executor.execute(() -> {
5    try {
6        List<User> users = parseUsers(responseBody);
7        mainHandler.post(() -> adapter.submitList(users));
8    } catch (Exception e) {
9        mainHandler.post(() -> showError(e.getMessage()));
10    }
11});

The important design point is to keep:

  • network I/O
  • JSON parsing
  • UI updates

as separate steps instead of mixing them into one method.

When a Mapping Library Is Better

Manual iteration is fine for irregular or dynamic payloads, but if the schema is stable, a library such as Gson or Moshi is often cleaner:

java
1class User {
2    int id;
3    String name;
4}
5
6Type listType = new TypeToken<List<User>>() {}.getType();
7List<User> users = new Gson().fromJson(response, listType);

That is often easier to maintain than repeated JSONObject field extraction when the API contract is stable.

Common Pitfalls

The biggest mistake is using strict get* methods everywhere even when the payload contains optional fields.

Another issue is parsing large JSON arrays on the Android main thread, which can freeze the UI.

People also often combine parsing, networking, and UI updates in one giant method, which makes the code harder to test and debug.

Finally, nested arrays and objects need explicit handling. Assuming every element is a flat object is a common source of runtime errors.

Summary

  • Iterate a JSONArray with an index loop from 0 to length() - 1.
  • Use opt* methods when fields may be missing or inconsistent.
  • Handle nested arrays and objects with explicit inner parsing steps.
  • Map JSON to model objects when the code should remain clean and testable.
  • Keep large parsing work off the Android main thread.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.