Skip to content

Gson – Convert HashMap to JSON

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

How to convert a Map/HashMap to JSON?

Converting a Java Map or HashMap to JSON can be done using the toJson method of the Gson class. The below given example converts a simple map object to a JSON representation using the same.

Output

As we can see from the output, it created a JSON object from the map object. Also, note that since the firstName and lastName values were strings in the HashMap object, there are wrapped in the double quotes in the JSON, while since the age was a number in the map, it is not wrapped in the double quotes in the JSON.

The Gson library can also convert a map of custom objects to JSON using the same toJson method. Consider the below given example that converts the HashMap of custom Student objects to the JSON.

Output

As we can see from the output, the Gson library automatically converted the “subjects” Java list to a JSON array.

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

About the author

Leave a Reply

Your email address will not be published.