Using Jackson tree model APIs to query and update data

You will use the com.fasterxml.jackson.databind.ObjectMapper class to convert the JSON data into a tree representation. This class has a variety of APIs to build a tree from the JSON data. The tree representation built from JSON is made up of com.fasterxml.jackson.databind.JsonNode instances. This is similar to the DOM nodes in an XML DOM tree. You can also navigate through JsonNode to identify specific elements present in the tree hierarchy. The following example illustrates the use of Jackson tree model APIs.

This example generates a tree hierarchy for the JSON array of employee objects and then queries the generated tree for the employee nodes with the null email value. This example updates all the null email values with the system-generated email addresses for later processing.

The readTree(InputStream in) instance defined on the com.fasterxml.jackson.databind.ObjectMapper class helps you to deserialize the JSON content as a tree (expressed using a set of JsonNode instances). To query JsonNode for a specific field name, you can call path(String fieldName) on the underlying JsonNode instance. The following code snippet will help you understand the use of these APIs:

//Other imports are removed for brevity 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

// Read in the JSON employee array form emp-array.json file
InputStream inputStream =
getClass().getResourceAsStream("/emp-array.json");
//Create ObjectMapper instance
//ObjectMapper provides functionality for creating tree
//structure for JSON content
ObjectMapper objectMapper = new ObjectMapper();

//Read JSON content in to tree
JsonNode rootNode = objectMapper.readTree(inputStream);

//Check if the json content is in array form
if (rootNode.isArray()) {
//Iterate over each element in the array
for (JsonNode objNode : rootNode) {
//Find out the email node by traversing tree
JsonNode emailNode = objNode.path("email");
//if email is null, then update with
//a system generated email
if(emailNode.textValue() == null ){
String generatedEmail=getSystemGeneratedEmail();
((ObjectNode)objNode).put("email", generatedEmail );
}
}
}
//Write the modified tree to a json file
objectMapper.writeValue(new File("emp-modified-array.json"),
rootNode);
if(inputStream != null)
inputStream.close();

The tree model API discussed in this section produces a generalized tree representation for the JSON content. To learn how to generate a more specific object representation for JSON, refer to the next section.

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

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