【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

posted @   逆火狂飙  阅读(2024)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2016-03-01 配置Tomcat6的管理用户
2016-03-01 在CentOS6.5上安装Tomcat6
2016-03-01 转载:如何运用VI编辑器进行查找替换
2016-03-01 打开Apache自带的Web监视器
2016-03-01 查看CentOS上Apache位置,版本,停止,启动
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示