How to get count all json nodes using Jackson framework

爱⌒轻易说出口 提交于 2021-01-29 04:45:26

问题


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"
        }
    ]
}

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

Giving me size = 1.

Can you please tell me what i am doing wrong?

Thanks


回答1:


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).



来源:https://stackoverflow.com/questions/39056203/how-to-get-count-all-json-nodes-using-jackson-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!