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();
        }
    }

 

posted @ 2018-02-12 15:38  千里驹  阅读(14650)  评论(1编辑  收藏  举报