Jackson Tree Model: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 45: Line 45:
</pre>
</pre>


This is a standard tree traversing method:
<span id="tree_model_traversing_example"></span>This is a standard tree traversing method:


{{Internal|Jackson Tree Model Traversing Example|Tree Model Traversing Example}}
{{Internal|Jackson Tree Model Traversing Example|Tree Model Traversing Example}}

Revision as of 18:56, 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 is the main API that builds trees from JSON content.

import com.fasterxml.jackson.databind.ObjectMapper;

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:

Tree Model Traversing Example

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)

See path(String fieldName).

with(int index)

See with(String fieldName).

JSON to Java with Tree Model Code Example

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 via Introspection

The ObjectMapper is capable of reading JSON and changing the state of a hierarchical Java object, if coded according to the Java Beans conventions. The JSON field names and the hierarchical structure (Objects, Array) must match the internal structure of the Java object for this to work.

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper om = new ObjectMapper();
Token token = on.readValue(inputStream, Token.class);

This is a generic conversion method, assuming that the JSON content matches the internal structure of the type <T>:

public static <T> T fromJson(String json, Class<? extends T> c) throws JsonConversionException {

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new ByteArrayInputStream(json.getBytes()), c);
    }
    catch (Exception e) {
       throw new JsonConversionException(e);
    }
}

Java to JSON with Tree Model

ObjectMapper will introspect a Java object coded according to the Java Beans conventions and output it as JSON content.

The method names (without the "get") will be used as field names.

Example:

import com.fasterxml.jackson.databind.ObjectMapper;

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectMapper om = new ObjectMapper();
Object root = ... // some hierarchical object
om.writeValue(baos, root);
System.out.println(new String(baos.toByteArray()));

Java to JSON with Tree Model Code Example

https://github.com/NovaOrdis/playground/blob/master/json/jackson/tree-model-java-to-json/src/main/java/io/novaordis/playground/json/jackson/tree/java2json/Main.java