Categories: Json

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

View Comments

Share
Published by

Recent Posts

Spring Boot + AngularJS + Spring Data + JPA CRUD App Example

In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…

7 years ago

Spring Boot Rest API Example

Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…

7 years ago

Spring Boot WAR deployment example

Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…

7 years ago

Spring Boot Introduction + hello world example

Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…

7 years ago

Secure Spring REST API using OAuth2

Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…

8 years ago

AngularJS+Spring Security using Basic Authentication

This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…

8 years ago