Java TreeTraversingParser-class And Method Code Example

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TreeTraversingParser;


public class Example {
    public static void main(String[] args) throws IOException {
        String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\",\"zip\":10001}}";

        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        JsonNode rootNode = mapper.readTree(json);

        // Create a TreeTraversingParser instance
        TreeTraversingParser ttp = new TreeTraversingParser(rootNode);

        // Traverse the JSON tree
        JsonNode currentNode = ttp.getCurrentNode();
        while (ttp.nextToken() != null) {
            currentNode = ttp.getCurrentNode();

This example shows how to use the TreeTraversingParser class, which is a parser that allows you to traverse a JSON tree. The TreeTraversingParser class takes a JsonNode as a parameter in its constructor, which represents the root of the JSON tree.

The nextToken() method is used to traverse the tree in a depth-first order, and returns the current token. The getCurrentNode() method is used to get the current node in the tree. In this example, it will print all the leaf nodes of the JSON tree.

Note that, TreeTraversingParser allows to traverse the tree in a read-only way, you can't modify the JSON tree using it. If you need to modify the tree, you should use ObjectMapper to deserialize the JSON to a POJO or a Map and then modify it, then serialize it back to JSON.