Skip to content

Gson – Convert JSON to HashMap

Gson – convert JSON to HashMap example shows how to convert JSON to HashMap using the Gson library in Java. The example also shows how to convert JSON to HashMap of custom objects.

How to convert JSON to a Java HashMap?

Let’s start with the below given simple JSON.

In order to convert this student JSON to a HashMap, we need to use the fromJson method of the Gson class as given below.

Output

As you can see from the output, the JSON property name becomes the key of the HashMap, and the value becomes the respective value of the HashMap.

The above example deals with a very simple JSON structure. In the real world, JSON may be much more complex than this. Consider the below given JSON.

The above JSON object has student objects as properties. We want our HashMap to contain the property name as a map key and the student object as a map value. Lets parse this JSON to a HashMap.

Output

As we can see from the output, each student property of the JSON has become the map’s value.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.