Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson to HashMap

Tags:

java

android

gson

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

like image 907
Daniel Amerbauer Avatar asked Feb 18 '13 20:02

Daniel Amerbauer


People also ask

Can we convert JSON to map in Java?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.

How do you serialize with Gson?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.

Is Gson better than Jackson?

ConclusionBoth Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.

How do I add a JSON response to a map?

Make sure that you download the org. json jar file and put it in your classpath to be able to use the JSONObject. You can download the jar from here. In order to put each of those values into map as single key/value entry.


2 Answers

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.

like image 104
Matt Ball Avatar answered Sep 22 '22 05:09

Matt Ball


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} 
like image 33
alexb83 Avatar answered Sep 25 '22 05:09

alexb83