public static JsonNode searchJson(JsonNode tree, String searchKey) throws JsonProcessingException, IOException { if (tree == null) { return null; } if(tree.has(searchKey)) { return tree.get(searchKey); } if(tree.isContainerNode()) { for(JsonNode branch: tree) { JsonNode branchResult = searchJson(branch, searchKey); if (branchResult != null && !branchResult.isMissingNode()) { return branchResult; } } } return null; }
@Test public void testSearchJson() throws JsonProcessingException, IOException { String jsonString = "{\"test\":[{\"data1\":100,\"data2\":\"hello\",\"data3\": [1 , 2 , 3]}, " + "{\"data4\":0}]}"; JsonNode node = JSONMetricUtil.mappStringToJsonNode(jsonString); JsonNode r1 = JSONMetricUtil.searchJson(node, "data1"); JsonNode r2 = JSONMetricUtil.searchJson(node, "data2"); JsonNode r3 = JSONMetricUtil.searchJson(node, "data3"); JsonNode r4 = JSONMetricUtil.searchJson(node, "data4"); assertEquals(100, r1.intValue()); assertEquals("hello", r2.textValue()); assertEquals(1, r3.get(0).intValue()); assertEquals(0, r4.intValue()); }
public static JsonNode searchJson(JsonNode tree, String searchKey) throws JsonProcessingException, IOException { if (tree == null) { return null; } if(tree.has(searchKey)) { return tree.get(searchKey); } if(tree.isContainerNode()) { for(JsonNode branch: tree) { JsonNode branchResult = searchJson(branch, searchKey); if (branchResult != null && !branchResult.isMissingNode()) { return branchResult; } } } return null; }
public static JsonNode searchJson(JsonNode tree, String searchKey) throws JsonProcessingException, IOException { if (tree == null) { return null; } if(tree.has(searchKey)) { return tree.get(searchKey); } if(tree.isContainerNode()) { for(JsonNode branch: tree) { JsonNode branchResult = searchJson(branch, searchKey); if (branchResult != null && !branchResult.isMissingNode()) { return branchResult; } } } return null; }
@Test public void testSearchJson() throws JsonProcessingException, IOException { String jsonString = "{\"test\":[{\"data1\":100,\"data2\":\"hello\",\"data3\": [1 , 2 , 3]}, " + "{\"data4\":0}]}"; JsonNode node = JSONMetricUtil.mappStringToJsonNode(jsonString); JsonNode r1 = JSONMetricUtil.searchJson(node, "data1"); JsonNode r2 = JSONMetricUtil.searchJson(node, "data2"); JsonNode r3 = JSONMetricUtil.searchJson(node, "data3"); JsonNode r4 = JSONMetricUtil.searchJson(node, "data4"); assertEquals(100, r1.intValue()); assertEquals("hello", r2.textValue()); assertEquals(1, r3.get(0).intValue()); assertEquals(0, r4.intValue()); }