Introduction to the use of the Jackson library in Java and its tree model

  • 2020-04-01 04:36:04
  • OfStack

Jackson's first program
Before going into the details of the Jackson library, let's take a look at the application manipulation capabilities. In this example, we create a Student class. You will create a JSON string for the student's details, deserialize it to the student's object, and then serialize it to the JSON string.

Create a Java class file called JacksonTester in C:\> Jackson_WORKSPACE.

File: JacksonTester. Java


import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public class JacksonTester {
  public static void main(String args[]){
   ObjectMapper mapper = new ObjectMapper();
   String jsonString = "{"name":"Mahesh", "age":21}";

   //map json to student
   try {
     Student student = mapper.readValue(jsonString, Student.class);
     System.out.println(student);
     
     mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
     jsonString = mapper.writeValueAsString(student);
     System.out.println(jsonString);

   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
}

class Student {
  private String name;
  private int age;
  public Student(){}
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public int getAge() {
   return age;
  }
  public void setAge(int age) {
   this.age = age;
  }
  public String toString(){
   return "Student [ name: "+name+", age: "+ age+ " ]";
  } 
}

The verification results

Compile the following classes using javac:


C:Jackson_WORKSPACE>javac JacksonTester.java

Now run jacksonTester and see the results:

C:Jackson_WORKSPACE>java JacksonTester

Verify the output


Student [ name: Mahesh, age: 21 ]
{
 "name" : "Mahesh",
 "age" : 21
}

Steps - remember
Here are the important steps to consider.

Step 1: create the ObjectMapper object.
Create the ObjectMapper object. It is a reusable object. \


ObjectMapper mapper = new ObjectMapper();

Step 2: deserialize JSON to the object.
Get it from the JSON object using the readValue() method. JSON string/source with JSON string and object type as parameters.


//Object to JSON Conversion
Student student = mapper.readValue(jsonString, Student.class);

Step 3: serialize the object to JSON.
Use the writeValueAsString() method to get a JSON string representation of the object.


//Object to JSON Conversion 
jsonString = mapper.writeValueAsString(student);

Jackson tree model
The tree model prepares the memory tree representation of the JSON file. ObjectMapper builds the JsonNode node tree. This is the most flexible method. It is similar to the XML of a DOM parser.

Create a tree from JSON
The ObjectMapper provides a root node of the pointer tree after the JSON has been read. The root node can be used to traverse the complete tree. Consider the following code snippet to get the root node that provides the JSON string.


//Create an ObjectMapper instance
ObjectMapper mapper = new ObjectMapper(); 
String jsonString = "{"name":"Mahesh Kumar", "age":21,"verified":false,"marks": [100,90,85]}";
//create tree from JSON
JsonNode rootNode = mapper.readTree(jsonString);

Traversing the tree model
The root node is traversed the tree using a relative path, and each node obtained from this data is processed. Consider the following code snippet traversing the tree of the supplied root node.


JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.getTextValue());
 
JsonNode marksNode = rootNode.path("marks");
Iterator iterator = marksNode.getElements();

The sample
Create a directory called JacksonTester in Java class files C:\> Jackson_WORKSPACE.

File: JacksonTester. Java


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

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonTester {
  public static void main(String args[]){
   JacksonTester tester = new JacksonTester();
   try {
     ObjectMapper mapper = new ObjectMapper();
     String jsonString = "{"name":"Mahesh Kumar", "age":21,"verified":false,"marks": [100,90,85]}";
     JsonNode rootNode = mapper.readTree(jsonString);

     JsonNode nameNode = rootNode.path("name");
     System.out.println("Name: "+ nameNode.getTextValue());

     JsonNode ageNode = rootNode.path("age");
     System.out.println("Age: " + ageNode.getIntValue());

     JsonNode verifiedNode = rootNode.path("verified");
     System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes":"No"));

     JsonNode marksNode = rootNode.path("marks");
     Iterator<JsonNode> iterator = marksNode.getElements();
     System.out.print("Marks: [ ");
     while (iterator.hasNext()) {
      JsonNode marks = iterator.next();
      System.out.print(marks.getIntValue() + " "); 
     }
     System.out.println("]");
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
}

Verify the output

Compile the following classes using javac:
The same code at the page code block index 0
Now run jacksonTester and see the results:
The same code at the page code block index 1
Verify the output


Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to JSON conversion
In this example, we have used JsonNode and written it to a JSON file and read it back to create a tree.

Create a directory called JacksonTester in Java class files C:\> Jackson_WORKSPACE.

File: JacksonTester. Java


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

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

public class JacksonTester {
  public static void main(String args[]){
   JacksonTester tester = new JacksonTester();
   try {
     ObjectMapper mapper = new ObjectMapper();

     JsonNode rootNode = mapper.createObjectNode();
     JsonNode marksNode = mapper.createArrayNode();
     ((ArrayNode)marksNode).add(100);
     ((ArrayNode)marksNode).add(90);
     ((ArrayNode)marksNode).add(85);
     ((ObjectNode) rootNode).put("name", "Mahesh Kumar");
     ((ObjectNode) rootNode).put("age", 21);
     ((ObjectNode) rootNode).put("verified", false);
     ((ObjectNode) rootNode).put("marks",marksNode);

     mapper.writeValue(new File("student.json"), rootNode);

     rootNode = mapper.readTree(new File("student.json"));

     JsonNode nameNode = rootNode.path("name");
     System.out.println("Name: "+ nameNode.getTextValue());

     JsonNode ageNode = rootNode.path("age");
     System.out.println("Age: " + ageNode.getIntValue());

     JsonNode verifiedNode = rootNode.path("verified");
     System.out.println("Verified: " + (verifiedNode.getBooleanValue() ? "Yes":"No"));

     JsonNode marksNode1 = rootNode.path("marks");
     Iterator<JsonNode> iterator = marksNode1.getElements();
     System.out.print("Marks: [ ");
     while (iterator.hasNext()) {
      JsonNode marks = iterator.next();
      System.out.print(marks.getIntValue() + " "); 
     }
     System.out.println("]");
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
}

The verification results

Compile the following classes using javac:
The same code at the page code block index 0
Now run jacksonTester and see the results:
The same code at the page code block index 1
Verify the output

Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [100 90 85]
Transform from tree to Java object
In this example, we've used JsonNode and written it to a JSON file, read it back and then converted a Student object to create a tree.

Create a directory called JacksonTester in Java class files C:\> Jackson_WORKSPACE.

File: JacksonTester. Java


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

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

public class JacksonTester {
  public static void main(String args[]){
   JacksonTester tester = new JacksonTester();
   try {
     ObjectMapper mapper = new ObjectMapper();

     JsonNode rootNode = mapper.createObjectNode();
     JsonNode marksNode = mapper.createArrayNode();
     ((ArrayNode)marksNode).add(100);
     ((ArrayNode)marksNode).add(90);
     ((ArrayNode)marksNode).add(85);
     ((ObjectNode) rootNode).put("name", "Mahesh Kumar");
     ((ObjectNode) rootNode).put("age", 21);
     ((ObjectNode) rootNode).put("verified", false);
     ((ObjectNode) rootNode).put("marks",marksNode);

     mapper.writeValue(new File("student.json"), rootNode);

     rootNode = mapper.readTree(new File("student.json"));

     Student student = mapper.treeToValue(rootNode, Student.class);

     System.out.println("Name: "+ student.getName());
     System.out.println("Age: " + student.getAge());
     System.out.println("Verified: " + (student.isVerified() ? "Yes":"No"));
     System.out.println("Marks: "+Arrays.toString(student.getMarks()));
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
}

class Student {
  String name;
  int age;
  boolean verified;
  int[] marks;
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public int getAge() {
   return age;
  }
  public void setAge(int age) {
   this.age = age;
  }
  public boolean isVerified() {
   return verified;
  }
  public void setVerified(boolean verified) {
   this.verified = verified;
  }
  public int[] getMarks() {
   return marks;
  }
  public void setMarks(int[] marks) {
   this.marks = marks;
  }
}

The verification results

Compile the following classes using javac:
The same code at the page code block index 0
Now run jacksonTester and see the results:
The same code at the page code block index 1
Verify the output


Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]


Related articles: