Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

java - How do you tree walk JSON via Jackson 2 JsonNode?

This was a bit of an exercise in frustration made worse by the fact that I couldn't find any answers to this question. So I'm going to answer the question here.

What I find most difficult to understand was that JsonNode doesn't have any getName() or similar method which I was expecting given that JSON is a name:value data type. Though I realised after working out this solution that arrays aren't name:value.

See answer below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
package treeWalker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;

public class TreeWalker
{
    public JsonNode convertJSONToNode(String json) throws JsonProcessingException, IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);

        return jsonNode;
    }

    public void walkTree(JsonNode root)
    {
        walker(null, root);
    }

    private void walker(String nodename, JsonNode node)
    {
        String nameToPrint = nodename != null ? nodename : "must_be_root";
        System.out.println("walker - node name: " + nameToPrint);
        if (node.isObject())
        {
            Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();

            ArrayList<Map.Entry<String, JsonNode>> nodesList = Lists.newArrayList(iterator);
            System.out.println("Walk Tree - root:" + node + ", elements keys:" + nodesList);
            for (Map.Entry<String, JsonNode> nodEntry : nodesList)
            {
                String name = nodEntry.getKey();
                JsonNode newNode = nodEntry.getValue();

                // System.out.println("  entry - key: " + name + ", value:" + node);
                walker(name, newNode);
            }
        }
        else if (node.isArray())
        {
            Iterator<JsonNode> arrayItemsIterator = node.elements();
            ArrayList<JsonNode> arrayItemsList = Lists.newArrayList(arrayItemsIterator);
            for (JsonNode arrayNode : arrayItemsList)
            {
                walker("array item", arrayNode);
            }
        }
        else
        {
            if (node.isValueNode())
            {
                System.out.println("  valueNode: " + node.asText());
            }
            else
            {
                System.out.println("  node some other type");
            }
        }
    }
}

And a Unit test to exercise (with no asserts! Sorry).

package treeWalker;

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;


public class TreeWalkerTest
{
    TreeWalker treeWalker = new TreeWalker();

    private String getJSON()
    {
        String json = "{"a":"val_a","b":"val_b","c":[1,2,3]}";
        return json;
    }

    @Test
    public void testConvertJSONToNode() throws JsonProcessingException, IOException
    {
        String json = getJSON();

        JsonNode jNode = treeWalker.convertJSONToNode(json);

        System.out.println("jnode:" + jNode);

    }

    @Test
    public void testWalkTree() throws JsonProcessingException, IOException
    {
        JsonNode jNode = treeWalker.convertJSONToNode(getJSON());

        treeWalker.walkTree(jNode);
    }
}

Oh, and the build.gradle:

apply plugin: 'java'
apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.4.3'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.3'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.3'
    compile 'com.google.guava:guava:18.0'

    testCompile "junit:junit:4.11"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...