JSON String can also be parsed by Tree, analgous to DOM tree for XML parsing. Jackson provides the set of APIs that will take JSON string as input and it will parse it to form in-memory JSON tree. It provides set of APIs to navigate the tree.
We will see simple example to do so
Here App.java that takes input JSON string and prepares JSON tree for navigation.
package custom.jackson.learning;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper();
// input JSON string
String jsonString = "{\"firstName\":\"Suresh\", \"lastName\":\"Rana\", "
+ " \"skill\":[\"Java\",\"PHP\",\"SQL\"] , "
+ " \"certified\":\"true\", \"age\":21}";
//Prepare in-Memory JSON Tree
JsonNode rootNode = mapper.readTree(jsonString);
//Navigate the JSON Tree through Nodes and elements structure to read data.
JsonNode firstNameNode = rootNode.path("firstName");
System.out.println("First Name ::"+firstNameNode.textValue());
JsonNode lastNameNode = rootNode.path("lastName");
System.out.println("First Name ::"+lastNameNode.textValue());
JsonNode skillNode = rootNode.path("skill");
Iterator skillItr = skillNode.elements();
System.out.println("Skills are ::");
while(skillItr.hasNext()){
JsonNode skillName = skillItr.next();
System.out.print(skillName.textValue()+" ");
}
System.out.println();
JsonNode certifiedNode = rootNode.path("certified");
System.out.println("Certified ::"+certifiedNode.booleanValue());
JsonNode ageNode = rootNode.path("age");
System.out.println("age ::"+ageNode.intValue());
}
}
Output ::
