Processing JSON using JSON-B

The following example reads the JSON representation of the Employee object from the emp.json file and uses the javax.json.bind.JsonBuilder to create an instance of javax.json.bind.Jsonb to map the Employee object to JSON representation and vice-versa:

  1. Read the target JSON document using JsonReader
  2. Create an instance of JSON-B using JsonbBuilder
  3. Unmarshal the JSON object to the Employee Java object
  4. Create a Jsonb instance with formatting enabled
  5. Marshal the Employee Java object to JSON

The implementation of the preceding steps is demonstrated in the following program:

public class JSR367JsonbDefaultBindingExample {

private static final Logger logger = Logger.getLogger(JSR367JsonbDefaultBindingExample.class.getName());

public static void main(String[] args) throws IOException {
logger.setLevel(Level.INFO);

//Step-1:Read the Target JSON Document
String jsonFileName = "/emp.json";
InputStream inputStream = JSR374JsonPointerExample.class.getResourceAsStream(jsonFileName);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
JsonReader jsonReader = Json.createReader(reader);
JsonObject jsonObject = (JsonObject) jsonReader.read();

//Step-2: Create instance of Jsonb using JsonbBuilder
Jsonb jsonb = JsonbBuilder.create();

//Step-3:Map JSON to Employee Object
Employee employee = jsonb.fromJson(jsonObject.toString(), Employee.class);

logger.log(Level.INFO, "Employee Object constructed from JSON:{0}", employee);

//Step-4:Create Jsonb instance with formatting enabled
JsonbConfig config = new JsonbConfig().withFormatting(Boolean.TRUE);
jsonb = JsonbBuilder.create(config);

//Step-5:Map Employee Object to JSON
String employeeJson = jsonb.toJson(employee);
logger.log(Level.INFO, "JSON constructed from Employee object:{0}", employeeJson);
}

The preceding program reads the emp.json file and prints the Employee object and JSON, as shown ahead:

Output of the Program:
Employee Object constructed from JSON:Employee{employeeId=100, firstName=John, lastName=Chen, [email protected], hireDate=2008-10-16}
JSON constructed from Employee object:
{
"email": "[email protected]",
"employeeId": "100",
"firstName": "John",
"hireDate": "2008-10-16",
"lastName": "Chen"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.234.28