Introduction to the use of the Java Jackson Library and its tree model _java

Source: Internet
Author: User
Tags arrays

Jackson's first program
before entering the details of the Jackson Library, let's take a look at the application's operational capabilities. In this example, we create a student class. You will create a JSON string student's details and deserialize it into the student's object, and then serialize it to the JSON string.

Create a c:\>jackson_workspace named Jacksontester in the Java class file.

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+ '] ';

 } 
}

Validation results

Use Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java

Now run Jacksontester See the results:
Copy Code code as follows:

C:\jackson_workspace>java Jacksontester

Validating output

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

Steps-Need to remember
Here are the important steps to consider here.

Step 1th: Create the Objectmapper object.
Creates a Objectmapper object. It is an object that can be reused. \

Copy Code code as follows:

Objectmapper mapper = new Objectmapper ();


Step 2nd: Deserialize the JSON to the object.
Gets from the JSON object using the ReadValue () method. The JSON string and object type are used as parameter JSON strings/sources.

Object to JSON conversion
Student Student = Mapper.readvalue (jsonstring, Student.class);

Step 3rd: Serialize the object to JSON.
Use the Writevalueasstring () method to get the 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 constructs the Jsonnode node tree. This is the most flexible method. It is similar to the XML of the DOM parser.

Create a tree from JSON
Objectmapper provides a root node of a pointer tree after reading JSON. The root node can be used to traverse the complete tree. Consider the following code fragment to obtain 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);

Traversal Tree Model
use the relative path to the root node to traverse the tree and process the data to get each node. Consider the following code fragment to traverse the tree of the provided root node.

Jsonnode Namenode = Rootnode.path ("name");
System.out.println ("Name:" + namenode.gettextvalue ());
 
Jsonnode Marksnode = Rootnode.path ("Marks");
Iterator iterator = marksnode.getelements ();

Example
Create a c:\>jackson_workspace named Jacksontester in the Java class file directory.

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 ();

 }
  }
}

Verifying output results

Use Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java

Now run Jacksontester See the results:
Copy Code code as follows:

C:\jackson_workspace>java Jacksontester

Validating output

Name:mahesh Kumar
age:21
verified:no
Marks: [100 90 85]

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

Create a c:\>jackson_workspace named Jacksontester in the Java class file directory.

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 ();

 }
  }
}

Validation results

Use Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java

Now run Jacksontester See the results:
Copy Code code as follows:

C:\jackson_workspace>java Jacksontester

Validating output

Name:mahesh Kumar
Age:21
Verified:no
Marks: [100 90 85]
convert from tree to Java object
In this example, we have used jsonnode and write it to a JSON file, and then read back and convert a student object to create a tree.

Create a c:\>jackson_workspace named Jacksontester in the Java class file directory.

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;
  Int[] Getmarks () {return marks;
  } public void Setmarks (int[] marks) {this.marks = marks;

 }
}

Validation results

Use Javac to compile the following classes:

Copy Code code as follows:

C:\jackson_workspace>javac Jacksontester.java

Now run Jacksontester See the results:
Copy Code code as follows:

C:\jackson_workspace>java Jacksontester

Validating output

Name:mahesh Kumar
age:21
verified:no
Marks: [100 90 85]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.