Jackson Tree Model Traversing Example

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Example

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()) {
               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");
    }
}