Using Jackson streaming APIs to generate JSON

The following example illustrates Jackson streaming APIs for writing JSON data. This example reads a list of Employee objects, converts them into JSON representations, and then writes to the OutputStream object. The steps are as follows:

  1. The following code snippet generates com.fasterxml.jackson.core.JsonGenerator by using com.fasterxml.jackson.core.JsonFactory:
OutputStream outputStream = new 
FileOutputStream("emp-array.json");JsonGenerator jsonGenerator = new
JsonFactory().createGenerator(outputStream,
JsonEncoding.UTF8);
  1. The next step is to build the JSON representation for the list of employees. The writeStartArray() method writes the starting marker for the JSON array ([). Now, write the marker for the object ({) by calling writeStartObject(). This is followed by the name-value pairs for the object by calling an appropriate write method. To write the end marker for the object (}), call writeEndObject(). Finally, to finish writing an array, call writeEndArray():
jsonGenerator.writeStartArray(); 
List<Employee> employees = getEmployeesList();
for (Employee employee : employees) {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("employeeId",
employee.getEmployeeId()); jsonGenerator.writeStringField("firstName",
employee.getFirstName()); jsonGenerator.writeStringField("lastName",
employee.getLastName());
jsonGenerator.writeEndObject();

}
//JsonGenerator class writes the JSON content to the
//specified OutputStream.

jsonGenerator.writeEndArray();
  1. Close the stream object after use:
//Close the streams to release associated resources 
jsonGenerator.close();
outputStream.close();
With this topic, we are ending our discussion on Jackson. In this section, we discussed the various categories of APIs for processing JSON. An in-depth coverage of the Jackson API is beyond the scope of this book. More details on Jackson are available at https://github.com/FasterXML/Jackson.

The link that answers some of the generic queries that you may have around Jackson is https://github.com/FasterXML/jackson/wiki/FAQ.

In the next section, we will discuss Gson, yet another framework 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.137.183.10