Skip to content

Instantly share code, notes, and snippets.

@codinko
Last active January 20, 2020 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinko/4f3784ac13896aa88a635a515d0562f7 to your computer and use it in GitHub Desktop.
Save codinko/4f3784ac13896aa88a635a515d0562f7 to your computer and use it in GitHub Desktop.
Read elements from the Json Tree - say responseData.json
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