Java用Jackson遍歷json全部節點

<!-- jackson begin -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.1.4</version>
</dependency>
<!-- jackson end -->

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

 

public static void jsonLeaf(JsonNode node) { if (node.isValueNode()) { System.out.println(node.toString()); return; } if (node.isObject()) { Iterator<Entry<String, JsonNode>> it = node.fields(); while (it.hasNext()) { Entry<String, JsonNode> entry = it.next(); jsonLeaf(entry.getValue()); } } if (node.isArray()) { Iterator<JsonNode> it = node.iterator(); while (it.hasNext()) { jsonLeaf(it.next()); } } } public static void main(String[] args) { try { String json = FileUtils.readFileToString(new File("C://test.json"), "UTF-8"); ObjectMapper jackson = new ObjectMapper(); JsonNode node = jackson.readTree(txt); jsonLeaf(node); } catch(Exception e) { e.printStackTrace(); } }
相關文章
相關標籤/搜索