
- 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 Model
Introduction
Tree Model prepares a in-memory tree representation of the JSON document. ObjectMapper build tree of JsonNode nodes. It is most flexible approach. It is analogus to DOM parser for XML.
Create 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);
Get each node using relative path to the root node while traversing tree and process the data. Consider the following code snippet traversing the tree provided the root node.
JsonNode nameNode = rootNode.path("name"); System.out.println("Name: "+ nameNode.textValue()); JsonNode marksNode = rootNode.path("marks"); Iterator<JsonNode> iterator = marksNode.elements();
Example - Traversing Tree Model
JacksonTester.java
package com.tutorialspoint; 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; public class JacksonTester { public static void main(String args[]){ 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.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 marksNode = rootNode.path("marks"); Iterator<JsonNode> iterator = marksNode.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