I need to print everything in a JSON file using Jackson in Java. I am 90% of the way there. Here is my Json File:
{
"my-data": {
"phone-number": "5555555555",
"userId": "1234",
"version": "2",
"more-data": {
"transaction-data": [
{
"Merchant": "Walmart",
"authorized": "true",
"amount": "7.50",
"is_card_expired": false,
"credit_limit": "2000"
}
]
}
}
}
I am able to print everything that has a key, but need help cleanly dealing with the array inside transaction-data. Notice that is an array with no key. Therefore, it is tricky to get inside, and my iterator (Iterator<Map.Entry<String, JsonNode>> Iterator = node.fields()
) turns up empty. I cannot use node.elements()
, because I need to get the key for everything, even if it is not something to print out. To print everything, my result should look something like
"phone-number": "5555555555"
"userId": "1234"
"version": "2"
"Merchant": "Walmart",
"authorized": "true",
"amount": "7.50",
"is_card_expired": false,
"credit_limit": "2000"
The best I have been able to come up with is after declaring my interator, I check if it hasNext(), and if not, then I create another iterator of elements (Iterator<JsonNode> iterator2 = node.elements();
). While that has next I recursively call my method on each of the nodes inside that. This works, but I am not sure this is the best solution. How would you cleanly iterate through/traverse my JSON file to hit each and every node, regardless of if it is an object, an array, or a value node, and regardless of whether or not a key exists (if a key does not exist then I need not print it out, I just need to enter that container and print out the items inside of it
2
Answers
This can be solved using standard recursive approach.
Where given entry is either a Object or Array of Objects.
Following link has exact same problem statement as yours:
java using JSONObject to loop recursive through any jsondata
Hope this helps. Thanks.
You can quite easily do this with a JSON parser:
The parser has a method called
currentValue()
but that doesn’t work in the above example, it always returnsnull
.