0

JSON Response:

{
    "took": 24,
    "timed_out": false,
    "_shards": {
        "total": 3,
        "successful": 3,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.0,
        "hits": [
            {
                "_index": "alibaba",
                "_type": "alibaba",
                "_id": "[\"523486f0-aaaa-aaaa-bdc8-a39572623db\",\"test\",\"cloud\"]",
                "_score": 0.0,
                "_source": {
                      "Company" : "alibaba",
                      "myMap": {
                          "Key_1": "Vlaue_1",
                          "Key_2": "Vlaue_2",
                          "Key_3": "Vlaue_3",
                         }
                }
            }
        ]
 }   

From the above, I need to extract the map. What I did is as follows.

JSONObject response= (JSONObject) element.get("_source");
String company = response.optString("Company",null);
// Till this code works fine. But gives error in next line.
String company = response.optString("myMap");

I know I am trying to get map in string, which is cause of problem.

Hence, I want to know how can I retrieve 'myMap' from the JSON Object.

Thanks.

2 Answers2

0

Not sure which library you are using but, you should be able to extract the JSONObject

JSONObject response= (JSONObject) element.get("_source");
JSONObject company = (JSONObject) response.get("myMap");
shyam
  • 9,134
  • 4
  • 29
  • 44
0

First of all the json provided is not valid I somehow made it work and used the entire json you provided.

    JSONObject myMap = obj.getJSONObject("hits").getJSONArray("hits").getJSONObject(0).getJSONObject("_source").getJSONObject("myMap");

If you want a map you can use a mapper to change jsonObject to map as in Convert JSON to Map

  • The JSON provided was just for telling the scenario. The main part was to get ONLY myMap from json and store in some variable so that I can use as per my situation , in which I was failing to extract. – CaptainLevii Aug 07 '20 at 04:41