Ifeanyi Kalu
Ifeanyi Kalu

Reputation: 55

Json to HashMap

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); 

Upvotes: 2

Views: 74

Answers (1)

Ankur Singhal
Ankur Singhal

Reputation: 26067

1.) Parse Json String to create JSONObject.

2.) Iterate over JsonObject to create Map.

you might get here what you want

Upvotes: 2

Related Questions