Last active
January 20, 2020 02:57
-
-
Save codinko/4f3784ac13896aa88a635a515d0562f7 to your computer and use it in GitHub Desktop.
Read elements from the Json Tree - say responseData.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String jsonString = Util.readFileFromClassPathAndConvert2String(fileNameInCP); | |
JsonNode root = objectMapper.readTree(jsonString); | |
--------------------- | |
APPROACH-1 | |
--------------------- | |
JsonNode nodes = root.get("companies"); | |
// imp note that you are going to iterate over the node values, not the keys ... | |
Iterator<JsonNode> itr = nodes.iterator(); | |
while (itr.hasNext()) { | |
JsonNode node = itr.next(); | |
String name = node.get("companyname").textValue() | |
// store string value or print it | |
} | |
--------------------- | |
APPROACH-2 | |
--------------------- | |
Instead of iterator you can use as below | |
node.at("/companies").fields().forEachRemaining(e -> { | |
System.out.println(e.getKey() + "---" + e.getValue().get("companyname")); | |
// e.getKey() is abcd and e.getValue() is the obj, so e.getValue().get("companyname") is Hersheys | |
}); | |
--------------------- | |
APPROACH-3 | |
--------------------- | |
Map<String, Object> result = objectMapper.convertValue(root, Map.class); | |
for (String key : result.keySet()) { | |
// this give syou ability to get the keys.. and only the keys | |
} | |
---- | |
Assume responseData.json | |
{ | |
"companies": { | |
"abcd" : { | |
"companyname" : "Hersheys", | |
"flavors" : { | |
"xyz" : { | |
"flavorname" : "vanilla", | |
"id" : 101 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment