Jackson's first program
Before entering the details of learning the jackson library, let's take a look at the application operation features. In this example, we create a Student class. A JSON string will be created and deserialized to the student's object, and then serialized to the JSON string.
Create a Java class file named JacksonTester 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+ " ]"; } }Verification results
Use javac to compile the following class:
The code copy is as follows:
C:/Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the result:
The code copy is as follows:
C:/Jackson_WORKSPACE>java JacksonTester
Verify the output
Student [ name: Mahesh, age: 21 ]{ "name" : "Mahesh", "age" : 21}Steps - Here are the important steps to consider here.
Step 1: Create an ObjectMapper object.
Create an ObjectMapper object. It is a reusable object. /
The code copy is as follows:
ObjectMapper mapper = new ObjectMapper();
Step 2: Deserialize JSON to the object.
Use the readValue() method to get from the JSON object. JSON string/source is passed as parameter JSON string and object type.
//Object to JSON ConversionStudent student = mapper.readValue(jsonString, Student.class);
Step 3: 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 builds the JsonNode node tree. This is the most flexible approach. It's similar to the XML of the DOM parser.
Create a tree from JSON
ObjectMapper provides a pointer tree root node after reading JSON. 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 instanceObjectMapper mapper = new ObjectMapper(); String jsonString = "{/"name/":/"Mahesh Kumar/", /"age/":21,/"verified/":false,/"marks/": [100,90,85]}";//create tree from JSONJsonNode rootNode = mappper.readTree(jsonString); Traversal tree model
Use relative paths to the root node in the traversal tree and process the data to obtain each node. Consider the following code snippet traversal of the provided root node's tree.
JsonNode nameNode = rootNode.path("name");System.out.println("Name: "+ nameNode.getTextValue()); JsonNode marksNode = rootNode.path("marks"); Iterator iterator = marksNode.getElements();Example creates a file directory called JacksonTester in Java class 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 = mappper.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 result
Use javac to compile the following class:
The code copy is as follows:
C:/Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the result:
The code copy is as follows:
C:/Jackson_WORKSPACE>java JacksonTester
Verify the output
Name: Mahesh KumarAge: 21Verified: NoMarks: [ 100 90 85 ]
Tree to JSON conversion
In this example, we have used JsonNode and written it to a JSON file and read back to create a tree.
Create a directory called JacksonTester in the Java class file 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(); } }}Verification results
Use javac to compile the following class:
The code copy is as follows:
C:/Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the result:
The code copy is as follows:
C:/Jackson_WORKSPACE>java JacksonTester
Verify the output
Name: Mahesh Kumar
Age: 21
Verified: No
Marks: [ 100 90 85 ]
Conversion from tree to Java object
In this example, we have used JsonNode and written it to a JSON file and read back and then converted a Student object to create a tree.
Create a directory called JacksonTester in the Java class file 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; }}Verification results
Use javac to compile the following class:
The code copy is as follows:
C:/Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the result:
The code copy is as follows:
C:/Jackson_WORKSPACE>java JacksonTester
Verify the output
Name: Mahesh KumarAge: 21Verified: NoMarks: [ 100 90 85 ]