如何使用Jackson框架获取所有json节点的计数 [英] How to get count all json nodes using Jackson framework

查看:64
本文介绍了如何使用Jackson框架获取所有json节点的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的user.json

Here is my user.json

{  
    "id":1,
    "name":{  
        "first":"Yong",
        "last":"Mook Kim"
    },
    "contact":[  
        {  
            "type":"phone/home",
            "ref":"111-111-1234"
        },
        {  
            "type":"phone/work",
            "ref":"222-222-2222"
        }
    ]
},
{  
    "id":2,
    "name":{  
        "first":"minu",
        "last":"Zi Lap"
    },
    "contact":[  
        {  
            "type":"phone/home",
            "ref":"333-333-1234"
        },
        {  
            "type":"phone/work",
            "ref":"444-444-4444"
        }
    ]
}

我想算一下其中有多少个json对象.例如,上面的json有2个json对象id = 1和id = 2.

I would like count how many json object is in there. For example the above json has 2 json object id = 1 and id =2.

//tree model approach
ObjectMapper mapper = new ObjectMapper();    
JsonNode rootNode = mapper.readTree(new File("user.json"));    
List<JsonNode> listOfNodes = rootNode.findParents("first");
System.out.println(listOfNodes.size());

给我尺码= 1.

你能告诉我我在做什么错吗?

Can you please tell me what i am doing wrong?

谢谢

推荐答案

您的Java代码正确,但是您的json文件无效. Jackson仅解析第一个有效元素("Yong").

Your java code is correct but your json file is invalid. Jackson parses only first valid element ("Yong").

要解决此问题,只需在文件的开头添加[,在文件的末尾添加](将其设置为数组).

To fix this just add [ at the begining and ] at the end of file (make it array).

这篇关于如何使用Jackson框架获取所有json节点的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆