樹模型準備JSON文件的內(nèi)存樹表示。 ObjectMapper構建JsonNode節(jié)點樹。這是最靈活的方法。它類似于DOM解析器的XML。
ObjectMapper提供一個指針樹的根節(jié)點在讀取JSON之后。根節(jié)點可用于遍歷完全樹??紤]下面的代碼片段獲得提供JSON字符串的根節(jié)點。
//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);
使用相對路徑來根節(jié)點在遍歷樹,并處理該數(shù)據(jù)得到的每個節(jié)點??紤]下面的代碼片段遍歷提供的根節(jié)點的樹。
JsonNode nameNode = rootNode.path("name"); System.out.println("Name: "+ nameNode.getTextValue()); JsonNode marksNode = rootNode.path("marks"); Iteratoriterator = marksNode.getElements();
創(chuàng)建一個名為JacksonTester在Java類文件目錄 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 = 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