How to create correct JSONArray in Java using JSONObject How to create correct JSONArray in Java using JSONObject arrays arrays

How to create correct JSONArray in Java using JSONObject


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();


I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.

String strJSON = ""; // your string goes hereJSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();// once you get the array, you may check items likeJSONOBject jObject = jArray.getJSONObject(0);

Hope this helps :)


Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject  getPerson(String firstName, String lastName){   JSONObject person = new JSONObject();   person .put("firstName", firstName);   person .put("lastName", lastName);   return person ;} public JSONObject getJsonResponse(){    JSONArray employees = new JSONArray();    employees.put(getPerson("John","Doe"));    employees.put(getPerson("Anna","Smith"));    employees.put(getPerson("Peter","Jones"));    JSONArray managers = new JSONArray();    managers.put(getPerson("John","Doe"));    managers.put(getPerson("Anna","Smith"));    managers.put(getPerson("Peter","Jones"));    JSONObject response= new JSONObject();    response.put("employees", employees );    response.put("manager", managers );    return response;  }