【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM