পৃষ্ঠাসমূহ

Search Your Article

CS

 

Welcome to GoogleDG – your one-stop destination for free learning resources, guides, and digital tools.

At GoogleDG, we believe that knowledge should be accessible to everyone. Our mission is to provide readers with valuable ebooks, tutorials, and tech-related content that makes learning easier, faster, and more enjoyable.

What We Offer:

  • 📘 Free & Helpful Ebooks – covering education, technology, self-development, and more.

  • 💻 Step-by-Step Tutorials – practical guides on digital tools, apps, and software.

  • 🌐 Tech Updates & Tips – simplified information to keep you informed in the fast-changing digital world.

  • 🎯 Learning Support – resources designed to support students, professionals, and lifelong learners.

    Latest world News 

     

Our Vision

To create a digital knowledge hub where anyone, from beginners to advanced learners, can find trustworthy resources and grow their skills.

Why Choose Us?

✔ Simple explanations of complex topics
✔ 100% free access to resources
✔ Regularly updated content
✔ A community that values knowledge sharing

We are continuously working to expand our content library and provide readers with the most useful and relevant digital learning materials.

📩 If you’d like to connect, share feedback, or suggest topics, feel free to reach us through the Contact page.

Pageviews

Tuesday, January 17, 2017

Jackson - Tree Model

The Tree Model prepares an in-memory tree representation of a JSON document. It is the most flexible approach among the three processing modes that Jackson supports. It is quite similar to DOM parser in XML.

Create a Tree from JSON

ObjectMapper provides a pointer to root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided 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 a Tree

Get each node using the relative path to the root node while traversing the tree and process the data. The following code snippet shows how to traverse a tree, provided you have information regarding the root node.
JsonNode nameNode = rootNode.path("name");
System.out.println("Name: "+ nameNode.getTextValue());
 
JsonNode marksNode = rootNode.path("marks");
Iterator iterator = marksNode.getElements();

Tree Model Example

Create a Java class file named JacksonTester in 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 Result

Compile the classes using javac compiler as follows −
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now execute the jacksonTester to see the result.
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output −
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to JSON Conversion

In the following example, we will create a Tree using JsonNode and write it to a JOSN file and read it back.
Create a Java class file named JacksonTester in 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(); }
   }
}

Verify the Result

Compile the classes using javac compiler as follows −
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result.
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output −
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

Tree to Java Objects

In the following example, we will perform the following operations −
  • Create a Tree using JsonNode
  • Write it to a JSON file
  • Read back the tree and then convert it to a Student object.
First of all, create a Java class file named JacksonTester in 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;
   }
}

Verify the Result

Compile the classes using javac compiler as follows −
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now execute the jacksonTester to see the result.
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output −
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]

No comments:

Post a Comment