Writing JSON data with Gson streaming APIs

You can use com.google.gson.stream.JsonWriter to write the JSON-encoded value to the stream. The following example demonstrates the use of Gson streaming APIs for writing JSON data. This example writes the JSON array representation of employee objects to the emp-array.json file. The steps are as follows:

  1. To write the JSON content, build the JsonWriter object, which takes the implementation of java.io.Writer as the input.
  2. Once the JsonWriter instance is created, start writing the JSON content. As this example writes an array of the employee objects, we start by invoking the beginArray() method. This call begins encoding a new array. Then, call beginObject() to start encoding a new object. This is followed by the encoding of the name and the value. To finish the encoding of the current object, call endObject(), and to finish the encoding of the current array, call endArray():
//Step 1: Build JsonWriter to read the JSON contents 
OutputStream outputStream = new FileOutputStream(
"emp-array.json");
BufferedWriter bufferedWriter= new BufferedWriter(
new OutputStreamWriter(outputStream));
//Creates JsonWriter object
JsonWriter writer = new JsonWriter(bufferedWriter);

//Step 2: Start writing JSON contents

//Starts with writing array
writer.beginArray();
List<Employee> employees = getEmployeesList();
for (Employee employee : employees) {
//start encoding the object
writer.beginObject();
//Write name:value pair to the object
writer.name("employeeId").value
(employee.getEmployeeId());
writer.name("firstName").value(employee.getFirstName());
writer.name("lastName").value(employee.getLastName());
writer.name("email").value(employee.getEmail());
//Finish encoding of the object
writer.endObject();
}
//Finish encoding of the array
writer.endArray();
writer.flush();
//close writer
writer.close();
An in-depth coverage of the Gson API is beyond the scope of this book. To learn more about Gson, visit https://code.google.com/p/google-gson/. The Gson API documentation is available at https://www.javadoc.io/doc/com.google.code.gson/gson/2.3.1.

With this, we have finished our discussion on the three popular JSON processing frameworks that you may find today. We may revisit some of these tools and frameworks with more complex use cases later in the book. In the following section, let's explore the proposed enhancements in Java EE8 for processing JSON.

..................Content has been hidden....................

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