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

部分代码来源于自动化测试REST API工具Wisdom RESTClient

https://github.com/Wisdom-Projects/rest-client

猜你喜欢

转载自wangyudong.iteye.com/blog/2413372