0

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"
     ]
    }
   }
  ]
 }
}
  • 1
    any work around that we can improve, maybe some code ? – Traian GEICU Apr 28 '21 at 06:33
  • 1
    This looks like a result from elasticsearch, why don't you use their java-api? See this [tutorial from baeldung](https://www.baeldung.com/elasticsearch-java) on how to implement it – Lino Apr 28 '21 at 06:36
  • however if you don't want to use the elasticsearch-library, you'd have to use a JSON-Parser like [jackson](https://www.baeldung.com/jackson) or [gson](https://www.baeldung.com/gson-deserialization-guide). (I'm not affiliated with Baeldung they just have great tutorials in my opinion ;) ) – Lino Apr 28 '21 at 06:38
  • any sample code for this requirement without using elasticsearch@Lino –  Apr 28 '21 at 06:50
  • Does this answer your question? [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – Willy satrio nugroho Apr 28 '21 at 12:39

1 Answers1

0

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]
Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12