Java
Chilkat2 Java
JSON: Array of Objects
See more JSON Examples
Here we have a JSON object that contains an array, where each element in the array is a JSON object. This example demonstrates how to access the objects contained within an array.
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonArray;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
JsonObject json = new JsonObject();
// This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
// The presence of whitespace chars for pretty-printing makes no difference to the Load
// method.
String jsonStr = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\",\"lastName\":\"Jones\"}]}";
try {
json.load(jsonStr);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Get the "employees" array.
JsonArray employees = json.arrayOf("employees");
if (employees == null) {
System.out.println("employees member not found.");
return;
}
// Iterate over each employee, getting the JSON object at each index.
int numEmployees = employees.getSize();
int i = 0;
while (i < numEmployees) {
JsonObject empObj = employees.objectAt(i);
System.out.println("employee[" + i + "] = " + empObj.stringOf("firstName") + " " + empObj.stringOf("lastName"));
empObj.close();
i = i + 1;
}
employees.close();
}
}