Jackson Tree Model Example

Conceptually, JSON can be represented as a Tree (similar to DOM tree). Therefore, it is possible to traverse to individual nodes in the tree in order to access/edit their values.

Jackson library provides api to do it. JsonNode refers to an individual node in tree which can be accessed using node name.ObjectMappers readTree and writeTree can be used to read and write JSON tree.

Let’s see how it can be done in Java

Step 1: Include JACKSON dependency in pom.xml

There are several jar in JACKSON library. For this example, we are only using databind.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.websystique.xml</groupId>
  <artifactId>JsonJacksonTreeMappingExample</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>JsonJacksonTreeMappingExample</name>

  <dependencies>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.5.3</version>
	</dependency>
  </dependencies>
 </project>

Step 2: Prepare Input

Below is the content of file(result.json) we will use in this example

{"car":"Audi","model":"2010","price":"30000","colors":["Grey","White","Black"]}

Step 3: Read JSON Tree using Tree Model

Read individual nodes by name using JsonNode.path("name of node").

package com.websystique.json.jackson;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonJacksonTreeMappingDemo {

	public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();

		/**
		 * Read values from conceptual JSON tree
		 */
		JsonNode rootNode = mapper.readTree(new File("result.json"));
		
		JsonNode carNode = rootNode.path("car");
		System.out.println(carNode.asText());

		JsonNode priceNode = rootNode.path("price");
		System.out.println(priceNode.asText());
		
		JsonNode modelNode = rootNode.path("model");
		System.out.println(modelNode.asText());
		
		JsonNode colorsNode = rootNode.path("colors");
		Iterator<JsonNode> colors = colorsNode.elements();
		
		while(colors.hasNext()){
			System.out.println(colors.next().asText());
		}
		
	}
}

Below is the output:

Audi
30000
2010
Grey
White
Black

Step 4: Write JSON Tree using Tree Model

Create conceptual tree using rootnode, then adding elements on different levels. Use JsonGenerator to write the content.

package com.websystique.json.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonJacksonTreeMappingDemo {

	public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();

		/**
		 * Write values in JSON tree
		 */
		JsonGenerator generator = mapper.getFactory().createGenerator(System.out);
		
		JsonNode treeRootNode = mapper.createObjectNode(); 
		((ObjectNode) treeRootNode).put("car", "Alfa Romio");
		((ObjectNode) treeRootNode).put("price", "54000");
		((ObjectNode) treeRootNode).put("model", "2013");
		ArrayNode arrayNode = ((ObjectNode) treeRootNode).putArray("colors");
		arrayNode.add("GRAY");
		arrayNode.add("BLACK");
		arrayNode.add("WHITE");
		mapper.writeTree(generator, treeRootNode);
		
	}
}

Below is the output

{"car":"Alfa Romio","price":"54000","model":"2013","colors":["GRAY","BLACK","WHITE"]}

That’s it. In the next post we will learn about Jackson Streaming API.

References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?