【java/objectMapper】使用objectMapper解析elasticsearch返回的文本内容
【请求网址】
http://192.168.32.130:9200/moft/emp/_search?pretty
【返回的json】
{
"took" : 39,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 13,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "moft",
"_type" : "emp",
"_id" : "111",
"_score" : 1.0,
"_source" : {
"name" : "hy",
"age" : "25"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "112",
"_score" : 1.0,
"_source" : {
"name" : "巴菲特",
"age" : "27"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "113",
"_score" : 1.0,
"_source" : {
"name" : "比尔盖茨",
"age" : "29"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "200",
"_score" : 1.0,
"_source" : {
"name" : "emp0",
"age" : "20"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "201",
"_score" : 1.0,
"_source" : {
"name" : "emp1",
"age" : "21"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "202",
"_score" : 1.0,
"_source" : {
"name" : "emp2",
"age" : "22"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "203",
"_score" : 1.0,
"_source" : {
"name" : "emp3",
"age" : "23"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "204",
"_score" : 1.0,
"_source" : {
"name" : "emp4",
"age" : "24"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "205",
"_score" : 1.0,
"_source" : {
"name" : "emp5",
"age" : "25"
}
},
{
"_index" : "moft",
"_type" : "emp",
"_id" : "206",
"_score" : 1.0,
"_source" : {
"name" : "emp6",
"age" : "26"
}
}
]
}
}
【Code】
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.client.RestTemplate; import java.util.Iterator; public class Test2 { public static void main(String[] args) throws Exception{ RestTemplate restTemplate = new RestTemplate(); String json = restTemplate.getForObject("http://192.168.32.130:9200/moft/emp/_search",String.class); ObjectMapper mapper = new ObjectMapper(); // 获取根节点 JsonNode node = mapper.readTree(json); JsonNode listNode=node.get("hits").path("hits"); Iterator<JsonNode> iterator = listNode.elements(); while (iterator.hasNext()) { JsonNode student = iterator.next(); // 获取节点文本 String name=student.get("_source").get("name").asText(); System.out.println(name); } } }
【输出】
hy
巴菲特
比尔盖茨
emp0
emp1
emp2
emp3
emp4
emp5
emp6
END
分类:
Java.JSON
, Java.ElasticsSearch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
2020-02-25 Oracle的timestamp字段更新实验 结论:只有逐条更新才能保证timestamp字段有差别,批量更新只会得到一致的时间,此操作无关时间精度.
2015-02-25 【高中数学/极值问题】已知:a,b皆为正实数,且2a+b=1,求:a/(2-2a)+b/(2-b)的最小值?
2014-02-25 【Canvas与光阑】立方体六彩光阑