Create JSON Using JSONObjectBuilder and JSONArrayBuilder in Java



The JsonObjectBuilder can be used for creating JsonObject models whereas the JsonArrayBuilder can be used for creating JsonArray models. The JsonObjectBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonObject instance using the Json.createObjectBuilder().build(). The JsonArrayBuilder can be created using the Json class, it contains methods to create the builder object and build an empty JsonArray instance using Json.createArrayBuilder().build().

Example

import java.io.*;
import javax.json.*;
public class JsonObjectTest {
   public static void main(String[] args) {
      JsonObject empObject = Json.createObjectBuilder().add("empName", "Jai")
                                 .add("empAge", "25")
                                 .add("empSalary", "40000")
                                 .add("empAddress",
                                      Json.createObjectBuilder().add("street", "IDPL Colony")
                                                           .add("city", "Hyderabad")
                                                           .add("pinCode", "500072")
                                                           .build()
                                     )
                                 .add("phoneNumber",
                                      Json.createArrayBuilder().add("9959984000")
                                                               .add("7702144400")
                                                               .build()
                                      )
                                 .build();
      System.out.println(empObject);
   }
}

Output

{"empName":"Jai","empAge":"25","empSalary":"40000","empAddress":{"street":"IDPL Colony","city":"Hyderabad","pinCode":"500072"},"phoneNumber":["9959984000","7702144400"]}
Updated on: 2020-07-07T11:43:40+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements