Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the example code to create JSON Object:

{

    "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"}

    ]

}

Can anyone tell me how to create a JSONObject in Java for the JSONArray string? 

1 Answer

0 votes
by (19.7k points)

Here’s the code implementation in Java 6, which uses the put method: 

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

The below code implementation is in Java 7, which uses the add method: 

  JsonObject jo = Json.createObjectBuilder()

  .add("employees", Json.createArrayBuilder()

   .add(Json.createObjectBuilder()

    .add("firstName", "John")

     .add("lastName", "Doe")))

     .build();

If you want to learn more about Javathen go through this Java tutorial by Intellipaat for more insights. 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
+7 votes
2 answers
0 votes
1 answer
asked Feb 25, 2021 in Java by Jake (7k points)

Browse Categories

...