- Jackson - Home
- Jackson - Overview
- Jackson - Environment Setup
- Jackson - First Application
- Jackson - ObjectMapper Class
- Jackson - Object Serialization
Jackson - Data Binding
Jackson - Tree Model
Jackson - Streaming API
Jackson Useful Resources
Jackson - Tree to JSON
Introduction
In this example, we've created a Tree using JsonNode and write it to a json file and read back.
Example - Creating a Tree and Write to JSON
JacksonTester.java
package com.tutorialspoint;
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;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.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.textValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("Age: " + ageNode.intValue());
JsonNode verifiedNode = rootNode.path("verified");
System.out.println("Verified: " + (verifiedNode.booleanValue() ? "Yes":"No"));
JsonNode marksNode1 = rootNode.path("marks");
Iterator<JsonNode> iterator = marksNode1.elements();
System.out.print("Marks: [ ");
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.intValue() + " ");
}
System.out.println("]");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Run the JacksonTester and verify the output −
Name: Mahesh Kumar Age: 21 Verified: No Marks: [ 100 90 85 ]
Advertisements