【java/json】遍历JsonNode数组
【数据来源JSON文】
{ "took" : 305, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 4, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "hw", "_type" : "emp", "_id" : "1", "_score" : 1.0, "_source" : { "name" : "andy", "age" : "21" } }, { "_index" : "hw", "_type" : "emp", "_id" : "2", "_score" : 1.0, "_source" : { "name" : "bill", "age" : "22" } }, { "_index" : "hw", "_type" : "emp", "_id" : "3", "_score" : 1.0, "_source" : { "name" : "cindy", "age" : "23" } }, { "_index" : "hw", "_type" : "emp", "_id" : "4", "_score" : 1.0, "_source" : { "name" : "douglas", "age" : "24" } } ] } }
【目标】
把找到的每个员工的名字打印出来
【程序】
RestTemplate restTemplate = new RestTemplate(); String json = restTemplate.getForObject("http://192.168.245.129:9200/hw/emp/_search?pretty",String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); JsonNode arrayNode=root.get("hits").get("hits"); Iterator<JsonNode> it=arrayNode.elements(); while(it.hasNext()){ JsonNode itemNode=it.next(); JsonNode nameNode=itemNode.get("_source").get("name"); System.out.println(nameNode.asText()); }
【结果】
andy
bill
cindy
douglas
【源码下载】
https://files.cnblogs.com/files/heyang78/ObjectMapper_JsonNode_Resttemplate_220301.zip?t=1646142327
END