150

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.

soshial
  • 5,906
  • 6
  • 32
  • 40
user2010955
  • 3,871
  • 7
  • 34
  • 53

4 Answers4

275

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();
Grammin
  • 11,808
  • 22
  • 80
  • 138
  • 3
    maybe also wrap into try/catch? (or the method has to have throws statement) – Lukas1 Feb 18 '14 at 09:10
  • 9
    JSONArray does not have a put method. – ABC123 Jun 03 '14 at 19:37
  • 3
    use add instead of put – CleanX Jul 14 '14 at 10:04
  • I'm a little confused by the docs on JsonArray... can you explain which put method takes two strings as arguments? e.g. put("lastName", "Doe"); http://www.json.org/javadoc/org/json/JSONArray.html – user3388884 Aug 15 '14 at 15:47
  • @user3388884 JSONArray doesn't contain a put method that takes two strings. But I'm not using JSONArray there I'm using a JSONObject. http://www.json.org/javadoc/org/json/JSONObject.html – Grammin Aug 15 '14 at 17:02
  • Is there a way to implement JsonObject and JsonArray similar to JSONObject and JSONArray? Meaning creating empty objects and then adding components in subsequent methods, instaed of all at once as in JsonObject and JsonArray? – PT_C Sep 18 '15 at 15:37
  • 1
    @PT_C yep JsonObject jo = Json.createObjectBuilder(); jo.add("firstName", "John"); jo.add("lastName", "Doe"); jo.build(); – Grammin Sep 21 '15 at 21:27
  • What should I import to make my ide understand Json.createObjectBuilder()? – Pau Arlandis Martinez May 09 '16 at 08:57
  • What version of java are you using? You need to be using java 7 or above. – Grammin May 12 '16 at 13:57
  • @Jim JSONArray does have put method –  Dec 14 '17 at 10:33
  • Here's a short tutorial that demonstrates [creating a JSONObject and a JSONArray](https://www.youtube.com/watch?v=-qEpxIARKxE) using org.json. – drorw Nov 13 '18 at 12:29
  • @Grammin how to add ja to mainObj without key(employees)? like {[{--},{--},{--}]} – Arnold Brown Oct 14 '19 at 03:51
  • 1
    @ArnoldBrown In order to add an array to mainObj it has to have a key. – Grammin Oct 24 '19 at 22:04
17

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 here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);

Hope this helps :)

Naeem A. Malik
  • 995
  • 4
  • 19
16

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;
  }
Atheerth
  • 5
  • 5
Manasi
  • 765
  • 6
  • 17
5

Please try this ... hope it helps

JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();

jsonObj1=new JSONObject();
jsonObj2=new JSONObject();


array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);

Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;
MSD
  • 437
  • 6
  • 18