How do I access members of items in a JSONArray in Java?

I’m new to working with JSON in Java and unsure how to extract string values from a JSONArray Java object. My JSON structure looks like this:

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501,
        "loc": "NEW YORK STATE"
      }
    ]
  }
}

I can retrieve the "record" JSONArray using:

JSONObject req = new JSONObject(join(loadStrings(data.json), ""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

But I’m unsure how to loop through it and access the "id" and "loc" values. What’s the correct way to do this?

You’re on the right track! Once you have the JSONArray, you can loop through it using getJSONObject(index).

Here’s how you can access “id” and “loc” values:

for (int i = 0; i < recs.length(); i++) {
    JSONObject obj = recs.getJSONObject(i);
    int id = obj.getInt("id");
    String loc = obj.getString("loc");
    System.out.println("ID: " + id + ", Location: " + loc);
}
  • :heavy_check_mark: Simple and readable
  • :x: Throws exceptions if keys are missing

Good approach! But what if “id” or “loc” are missing or have unexpected types?

We should handle that:

for (int i = 0; i < recs.length(); i++) {
    JSONObject obj = recs.optJSONObject(i);
    if (obj != null) {
        int id = obj.optInt("id", -1); // Default -1 if missing
        String loc = obj.optString("loc", "Unknown"); // Default "Unknown" if missing
        System.out.println("ID: " + id + ", Location: " + loc);
    }
}
  • Avoids exceptions for missing keys
  • Provides default values

Both solutions work well, but if you prefer a more modern, functional approach, try Java Streams:

IntStream.range(0, recs.length())
    .mapToObj(recs::getJSONObject)
    .forEach(obj -> {
        int id = obj.optInt("id", -1);
        String loc = obj.optString("loc", "Unknown");
        System.out.println("ID: " + id + ", Location: " + loc);
    });
  • Concise & elegant (especially for large JSON data)
  • Avoids index-based looping