2

I have the following as a json output, how do I convert it to a HashMap using Gson:

{
    "result": {
        "haystack": [
            "SvqFd",
            "ucR3Y",
            "AzVB0",
            "DrDQL",
            "gc8LQ",
            "JqKdK",
            "9ZE4g",
            "820gw",
            "ekWkr",
            "qgDrR",
            "ENpyZ",
            "lf4b8",
            "SZsUt",
            "YO0cQ",
            "CD1O0",
            "Rvw8t",
            "euSC0",
            "3oemT",
            "6bUgC",
            "m8pFK"
        ],
        "needle": "lf4b8"
    }
}

I tried:

Type stringArrayMap = new TypeToken<Map<String, String[]>>(){}.getType(); 
Map<String,String[]> theCollection = gson.fromJson(output, stringArrayMap);

Edit: Each time I get this json output,its content is unique but same structure.

ANSWER

Answers and suggestions below worked but I played around with those and figured something else that worked as well;

Type stringStringObjectMap = new TypeToken<Map<String, Map<String, Object>>>(){}.getType(); 
Map<String, Map<String, Object>> theDictionary = gson.fromJson(output, stringStringObjectMap); 
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
  • 1
    Hope the below link helps http://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson – sankar Dec 16 '14 at 07:36

1 Answers1

2

1.) Parse Json String to create JSONObject.

2.) Iterate over JsonObject to create Map.

you might get here what you want

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116