Using Jackson streaming APIs to parse JSON data

The following example illustrates Jackson streaming APIs for reading JSON data. This example uses streaming APIs to generate a Java model for the JSON array of employee objects. As in the earlier examples, the emp-array.json file is used as the input source. The steps are as follows:

  1. Create the com.fasterxml.jackson.core.JsonParser instance by using com.fasterxml.jackson.core.JsonFactory. The JsonParser class reads the JSON content from the file input stream.
  2. The next step is to start parsing the JSON content read from the input source. The client may call the nextToken() method to forward the stream enough to determine the type of the next token. Based on the token type, the client can take an appropriate action. In the following sample code, the client checks for the start of an object (JsonToken.START_OBJECT) in order to copy the current JSON object to a new Employee instance. We use ObjectMapper to copy the content of the current JSON object to the Employee class:
//Step 1: Finds a resource with a given name. 
InputStream inputStream = getClass().getResourceAsStream(
"/emp-array.json");
//Creates Streaming parser
JsonParser jsonParser = new
JsonFactory().createParser(inputStream);

//Step 2: Start parsing the contents
//We will use data binding feature from ObjectMapper
//for populating employee object
ObjectMapper objectMapper = new ObjectMapper();
//Continue the parsing till stream is opened or
//no more token is available
while (!jsonParser.isClosed()) {
JsonToken jsonToken = jsonParser.nextToken();
// if it is the last token then break the loop
if (jsonToken == null) {
break;
}
//If this is start of the object, then create
//Employee instance and add it to the result list
if (jsonToken.equals(JsonToken.START_OBJECT)) {
//Use the objectMapper to copy the current
// JSON object to Employee object
employee = objectMapper.readValue(jsonParser,
Employee.class);
//Add the newly copied instance to the list
employeeList.add(employee);

}

}
//Close the stream after the use to release the resources
if (inputStream != null) {
inputStream.close();
}
if (jsonParser != null) {
jsonParser.close();
}
To learn all the possible token types returned by JsonParser in the Jackson framework, refer to http://fasterxml.github.io/jackson-core/javadoc/2.5/com/fasterxml/jackson/core/JsonToken.html.
..................Content has been hidden....................

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