![](/img/trans.png)
[英]Extract json string array value from json object using java
[英]How to Extract the Json Value from Json String using Java?
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"
]
}
}
]
}
}
使用org.json ,您可以執行以下操作:
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());
對於“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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.