簡體   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

我無法通過哈希映射進行迭代。我嘗試了iterator.next()。getKey()等,但無法正常工作。 我如何

您僅在訪問的JsonNode的外鍵上進行迭代。 並且由於您要打印出實際類的名稱,所以這就是為什么要獲取有關LinkedHashMap$Entry的記錄輸出的原因。 看一下metric_node.getFields();的返回類型metric_node.getFields();

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

您實際上是在該級別上遍歷每個節點。 但是,由於您兩次調用iterator.next() ,因此您同時按下了兩個鍵,並且循環終止了。 如果您嘗試在DATA2上運行此代碼,則會得到NoSuchElementException因為您要迭代的項目超出了迭代器實際知道的范圍。

因此,您實際上並沒有查看與這些鍵關聯的任何值。 如果更改循環處理JsonNodes您將看到每個字段上的鍵/值。 如果您有要通過的嵌套對象,則需要遍歷每個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();
}

輸出:

class_name=> = code1
content=> = 0

class_name=> = code2
content=> = 100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM