JSONArray nums = new JSONArray("[1,2,3]"); Integer num = nums.optInt(2); if (num != null) { System.out.println("Third element is " + num); } else { System.out.println("Array does not have a third element"); }
JSONArray people = new JSONArray("[{'name':'Alice'},{'name':'Bob'},{'age':30}]"); for (int i = 0; i < people.length(); i++) { JSONObject person = people.optJSONObject(i); if (person != null) { String name = person.optString("name"); if (name != null) { System.out.println(name); } } }In this case, the output would be "Alice" and "Bob", as the third element does not have a "name" field. The org.json package is a third-party library, and can be added to a project using Maven or Gradle.