Jackson Tree Model: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(23 intermediate revisions by the same user not shown)
Line 5: Line 5:
=Overview=
=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]].
This method converts a JSON document into a mutable in-memory tree representation of the JSON document, made of [[#JsonNode|JsonNode]] instances. Tree model is arguably the most flexible of all three methods. The tree model is similar to the [[XML DOM]].
 
=JsonNode=
 
The basic tree node data type.


=JSON to Java with Tree Model=
=JSON to Java with Tree Model=
Line 11: Line 15:
==JSON to Tree Model Conversion==
==JSON to Tree Model Conversion==


<tt>org.codehaus.jackson.map.ObjectMapper</tt> is the main API that builds trees from JSON content.  
<tt>org.codehaus.jackson.map.ObjectMapper.readTree()</tt> is the main API that builds <tt>JsonNode</tt> trees from JSON content.  


<pre>
<pre>
Line 18: Line 22:
InputStream is = ...
InputStream is = ...
ObjectMapper om = new ObjectMapper();
ObjectMapper om = new ObjectMapper();
JsonNode root = om.readTree(is);
JsonNode root = om.readTree(is);
</pre>
</pre>


The trees consists of <tt>JsonNode</tt>s. Each node has one of the following types, coded as the <tt>JsonNodeType</tt> enum:
The trees being built consists of <tt>JsonNode</tt> instances. Each node has one of the following types, coded as the <tt>JsonNodeType</tt> enum:


* NULL
* NULL
Line 45: Line 50:
</pre>
</pre>


This is a standard tree traversing method:
<span id="tree_model_traversing_example"></span>This is a standard tree traversing method:
 
<pre>
public static void traverse(int depth, boolean indent, JsonNode node) {
 
    JsonNodeType type = node.getNodeType();
 
    if (JsonNodeType.OBJECT.equals(type)) {
 
        System.out.println("\n" + indentation(depth) + "{");
 
        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();
 
            System.out.print(indentation(depth + 1) + "\"" + fieldName + "\": ");
 
            traverse(depth + 1, false, value);
 
            if (i.hasNext()) {
                System.out.print(",");
            }
            System.out.println();
        }
        System.out.print(indentation(depth) + "}");
    }
    else if (JsonNodeType.ARRAY.equals(type)) {
 
        System.out.println("\n" + indentation(depth) + "[");
 
        for(Iterator<JsonNode> i = node.iterator(); i.hasNext(); ) {
 
          traverse(depth + 1, true, i.next());


          if (i.hasNext()) {
{{Internal|Jackson Tree Model Traversing Example|Tree Model Traversing Example}}
              System.out.print(",");
          }
          System.out.println();
      }
      System.out.print(indentation(depth) + "]");
    }
    else {
        displayLeaf(depth, indent, node);
    }
}
 
public static void displayLeaf(int depth, boolean indent, JsonNode node) {
 
    JsonNodeType type = node.getNodeType();
 
    if (JsonNodeType.OBJECT.equals(type) || JsonNodeType.ARRAY.equals(type)) {
        throw new IllegalArgumentException(node + " not a leaf");
    }
 
    if (indent) {
        System.out.print(indentation(depth));
    }
 
    if (JsonNodeType.NULL.equals(type)) {
        System.out.print("null");
    }
    else if (JsonNodeType.BOOLEAN.equals(type)) {
        System.out.print(node.booleanValue());
    }
    else if (JsonNodeType.NUMBER.equals(type)) {
        System.out.print(node.numberValue());
    }
    else if (JsonNodeType.STRING.equals(type)) {
        System.out.print("\"" + node.textValue() + "\"");
    }
    else {
        throw new RuntimeException("NOT YET IMPLEMENTED");
    }
}
</pre>


===Tree Model Access Methods===
===Tree Model Access Methods===
Line 169: Line 100:
===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/04-tree-model-json-to-java/src/main/java/io/novaordis/playground/json/jackson/tree/json2java/Main.java JSON to Java Tree Model Example]}}
 
==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.
 
<pre>
import com.fasterxml.jackson.databind.ObjectMapper;
 
ObjectMapper om = new ObjectMapper();
Token token = on.readValue(inputStream, Token.class);
</pre>


=Java to JSON with Tree Model=
=Java to JSON with Tree Model=
<tt>ObjectMapper</tt> 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:


<pre>
<pre>
import com.fasterxml.jackson.databind.ObjectMapper;
JsonNode root = ...


ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectMapper om = new ObjectMapper();
ObjectMapper om = new ObjectMapper();
Object root = ... // some hierarchical object
 
om.writeValue(baos, root);
om.writeValue(baos, root);
System.out.println(new String(baos.toByteArray()));
System.out.println(new String(baos.toByteArray()));
</pre>
</pre>
Line 202: Line 118:
==Java to JSON with Tree Model Code Example==
==Java to JSON with Tree Model Code Example==


{{External|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}}
{{External|[https://github.com/NovaOrdis/playground/blob/master/json/jackson/03-tree-model-java-to-json/src/main/java/io/novaordis/playground/json/jackson/tree/java2json/Main.java Java to JSON Tree Model Example]}}

Latest revision as of 02:15, 14 November 2018

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.

JsonNode

The basic tree node data type.

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

JSON to Java Tree Model 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()));

Java to JSON with Tree Model Code Example

Java to JSON Tree Model Example