简体   繁体   English

解码杰克逊树模型

[英]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. 我无法通过哈希映射进行迭代。我尝试了iterator.next()。getKey()等,但无法正常工作。 How do I 我如何

You are only iterating over the outer keys of the JsonNode you are visiting. 您仅在访问的JsonNode的外键上进行迭代。 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 . 并且由于您要打印出实际类的名称,所以这就是为什么要获取有关LinkedHashMap$Entry的记录输出的原因。 Take a look at the return type of the metric_node.getFields(); 看一下metric_node.getFields();的返回类型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. 但是,由于您两次调用iterator.next() ,因此您同时按下了两个键,并且循环终止了。 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. 如果您尝试在DATA2上运行此代码,则会得到NoSuchElementException因为您要迭代的项目超出了迭代器实际知道的范围。

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. 如果更改循环处理JsonNodes您将看到每个字段上的键/值。 If you have nested objects that you wanted to go through, you would need to traverse through each JsonNode 如果您有要通过的嵌套对象,则需要遍历每个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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