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"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…