How to create correct JSONArray in Java using JSONObject

user2010955 picture user2010955 · Sep 24, 2013 · Viewed 471.2k times · Source

how can I create a JSON Object like the following, in Java using JSONObject ?

{
    "employees": [
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    ],
    "manager": [
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    ]
}

I've found a lot of example, but not my exactly JSONArray string.

Answer

Grammin picture Grammin · Sep 24, 2013

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();