Jackson Tree Model

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

This method converts a JSON document into a mutable in-memory tree representation of the JSON document. Tree model is arguably the most flexible of all three methods. The tree model is similar to the XML DOM.

JSON to Java with Tree Model

org.codehaus.jackson.map.ObjectMapper is the main API that builds trees from JSON content.

InputStream is = ...

ObjectMapper om = new ObjectMapper();

JsonNode root = om.readTree(is);

The trees consists of JsonNodes. Each node has one of the following types, coded as the JsonNodeType enum:

  • NULL
  • BOOLEAN
  • NUMBER
  • STRING
  • OBJECT
  • ARRAY
  • BINARY
  • POJO
  • MISSING

There is no "FIELD" node. If the node is an OBJECT, we get its fields with:

for(Iterator<Map.Entry<String, JsonNode>> i = node.fields(); i.hasNext(); ) {

    Map.Entry<String, JsonNode> field = i.next();
    String fieldName = field.getKey();
    JsonNode value = field.getValue();
    ...
}

This is a standard tree traversing method:


JSON to Java with Tree Model Code Example


Java to JSON with Tree Model