Gson to HashMap

Daniel Amerbauer picture Daniel Amerbauer · Feb 18, 2013 · Viewed 51.9k times · Source

Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I am using the Gson lib.

For example, given JSON:

{
"id":3,
"location":"NewYork"
}

resulting HashMap:

<"id", "3">
<"location", "NewYork">

Thanks

Answer

Matt Ball picture Matt Ball · Feb 18, 2013

Use TypeToken, as per the GSON FAQ:

Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(json, stringStringMap);

No casting. No unnecessary object creation.