Jackson Tree Model: Difference between revisions
Line 96: | Line 96: | ||
===JSON to Java with Tree Model Code Example=== | ===JSON to Java with Tree Model Code Example=== | ||
{{External|[https://github.com/NovaOrdis/playground/blob/master/json/jackson/tree-model-json-to-java/src/main/java/io/novaordis/playground/json/jackson/tree/json2java/Main.java | {{External|[https://github.com/NovaOrdis/playground/blob/master/json/jackson/tree-model-json-to-java/src/main/java/io/novaordis/playground/json/jackson/tree/json2java/Main.java JSON to Java Tree Model Example]}} | ||
=Java to JSON with Tree Model= | =Java to JSON with Tree Model= |
Revision as of 21:01, 26 February 2017
Internal
Overview
This method converts a JSON document into a mutable in-memory tree representation of the JSON document, made of JsonNode instances. 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
JSON to Tree Model Conversion
org.codehaus.jackson.map.ObjectMapper.readTree() is the main API that builds JsonNode trees from JSON content.
import com.fasterxml.jackson.databind.ObjectMapper; InputStream is = ... ObjectMapper om = new ObjectMapper(); JsonNode root = om.readTree(is);
The trees being built consists of JsonNode instances. 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:
Tree Model Access Methods
For Objects
get(String fieldName)
returns the value of the property if exists, or null if it does not, or if the node is not an Object node.
path(String fieldName)
is similar with get(...), with the difference that it returns MissingNode instead of null for missing values. MissingNode implements all JsonNode methods, but they return another MissingNode, making for a safe traversal, that will never throw NullPointerException. The result will at worst MissingNode.
with(String fieldName)
is similar with with(...), but instead of returning MissingNode, will actually create and add new ObjectNode. The method is useful for safe modifications: you can "materialize" sub-trees as necessary.
For Arrays
get(int index)
returns the value of the array element at "index" (0-based), or null the index is out of bounds, or the node is not an Array node.
path(int index)
with(int index)
JSON to Java with Tree Model Code Example
Java to JSON with Tree Model
JsonNode root = ... ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectMapper om = new ObjectMapper(); om.writeValue(baos, root); System.out.println(new String(baos.toByteArray()));