简体   繁体   中英

decoding Jackson Tree Model

 DATA1 = {"metrics": {"code1": 0, "code2" : 100}  }
 DATA2 = {"metrics": {"code1": [10,20,30]}}

CODE
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(m);

JsonNode metric_node = rootNode.path("metrics");
Iterator iterator  = metric_node.getFields();
while (iterator.hasNext()) {
     logger.info("class_name=> {}", iterator.next().getClass().getName());
     logger.info("content=> {}", iterator.next());
}


OUTPUT (for DATA1)
class_name=> java.util.LinkedHashMap$Entry
content=> code1=0
class_name=> java.util.LinkedHashMap$Entry
content=> code2=100

Don't know about DATA2

I am not able to iterate through the hashmap.I tried iterator.next().getKey() etc. but not working. How do I

You are only iterating over the outer keys of the JsonNode you are visiting. And since you are printing out the name of the actual class, that is why you are getting the logged output about the LinkedHashMap$Entry . Take a look at the return type of the metric_node.getFields();

Iterator<Map.Entry<String, JsonNode>> iterator  = metric_node.fields();

You are essentially iterating over each node at that level. But since you call iterator.next() twice, you are hitting both keys and the loop is terminating. If you tried to run this code on DATA2 , you would get a NoSuchElementException because you are iterating over more items than your iterator actually knows about.

So, you are not actually looking at any of the values associated with those keys. If you change how your loop processes the JsonNodes you will see what keys/values are at each field. If you have nested objects that you wanted to go through, you would need to traverse through each JsonNode

JsonNode rootNode = mapper.readTree(DATA1);

JsonNode metric_node = rootNode.path("metrics");
Iterator<Map.Entry<String, JsonNode>> iterator  = metric_node.fields();
while (iterator.hasNext()) {
    Map.Entry<String, JsonNode> next = iterator.next();
    System.out.println("class_name=> = " + next.getKey());
    System.out.println("content=> = " + next.getValue());
    System.out.println();
}

Output:

class_name=> = code1
content=> = 0

class_name=> = code2
content=> = 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM