user1459497 user1459497 - 3 months ago 21
Java Question

How to get count all json nodes using Jackson framework

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

Answer

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