Gson to HashMap

JavaAndroidGson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

If I use the TypeToken solution with a Map<Enum, Object> I get "duplicate key: null".

The best solution for me is:

String json = "{\"id\":3,\"location\":\"NewYork\"}";
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = (Map<String, Object>)gson.fromJson(json, map.getClass());

Result:

{id=3.0, location=NewYork}

Solution 3 - Java

I like:

private static class MyMap extends HashMap<String,String> {};
...
MyMap map = gson.fromJson(json, MyMap.class);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel AmerbauerView Question on Stackoverflow
Solution 1 - JavaMatt BallView Answer on Stackoverflow
Solution 2 - Javaalexb83View Answer on Stackoverflow
Solution 3 - JavaRicardo FodraView Answer on Stackoverflow