This is my json structure and I want to get the values of hierarchy_name from each json object in an Array, can someone help me with that using Java..
{
"hits": {
"total": {
"value": 218
},
"max_score": null,
"hits": [
{
"_index": "planlytx",
"_source": {
"hierarchy_name": "PRODUCT"
},
"fields": {
"attribute_name.keyword": [
"PRODUCT"
]
}
},
{
"_index": "planlytx",
"_source": {
"hierarchy_name": "PRODUCT"
},
"fields": {
"attribute_name.keyword": [
"PRODUCT-ALL"
]
}
}
]
}
}
Using org.json , you can do:
JSONArray hitsArray = new JSONObject(jsonStr).getJSONObject("hits").getJSONArray("hits");
List<String> keywords = IntStream.range(0, hitsArray.length())
.mapToObj(hitsArray::getJSONObject)
.map(json -> json.getJSONObject("fields")
.getJSONArray("attribute_name.keyword")
.toList())
.flatMap(objects -> objects.stream().map(Object::toString))
.collect(Collectors.toList());
For "hierarchy_name":
JSONArray hitsArray = new JSONObject(jsonStr).getJSONObject("hits").getJSONArray("hits");
List<String> keywords = IntStream.range(0, hitsArray.length())
.mapToObj(hitsArray::getJSONObject)
.map(json -> json.getJSONObject("_source").getString("hierarchy_name"))
.collect(Collectors.toList());
Output:
[PRODUCT, PRODUCT-ALL]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.