-
-
Save zelark/de2b53654be3975eab96660e62e54ca2 to your computer and use it in GitHub Desktop.
Jackson 2.0 JSON Traversal Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package parse; | |
import com.fasterxml.jackson.core.JsonFactory; | |
import com.fasterxml.jackson.core.JsonParser; | |
import com.fasterxml.jackson.core.JsonToken; | |
import com.fasterxml.jackson.databind.JsonNode; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import java.io.File; | |
import java.io.IOException; | |
import java.util.Iterator; | |
public class ParseJson { | |
public static void main(String[] args) throws IOException { | |
parseTree(new File("D:/tmp/tst.json")); | |
} | |
public static void parseTree(File file) throws IOException { | |
ObjectMapper m = new ObjectMapper(); | |
JsonNode rootNode = m.readTree(file); | |
printNode(rootNode, 0); | |
} | |
private static void printNode(JsonNode parentNode, int depth) { | |
if (parentNode.isArray()) { | |
printTabs(depth); | |
System.out.println("["); | |
Iterator<JsonNode> iter = parentNode.elements(); | |
while (iter.hasNext()) { | |
JsonNode node = iter.next(); | |
if (node.isObject() || node.isArray()) { | |
printNode(node, depth+1); | |
} else { | |
printTabs(depth); | |
System.out.print(node.asText()); | |
} | |
} | |
printTabs(depth); | |
System.out.println("]"); | |
} | |
if (parentNode.isObject()) { | |
printTabs(depth); | |
System.out.println("{"); | |
Iterator<String> iter = parentNode.fieldNames(); | |
while (iter.hasNext()) { | |
String nodeName = iter.next(); | |
JsonNode node = parentNode.path(nodeName); | |
printTabs(depth); | |
System.out.println(nodeName + ": " + node.asText()); | |
if (node.isObject() || node.isArray()) { | |
printNode(node, depth+1); | |
} | |
} | |
printTabs(depth); | |
System.out.println("}"); | |
} | |
} | |
private static void printTabs(int count) { | |
for (int i=0; i<count; i++) { | |
System.out.print("\t"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment