Java Gson toJson Example

In the example, we serialize a map into JSON with the Gson toJSon() method.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.
Check out the complete Gson tutorial at

Java Gson Maven dependency

This is a Maven dependency for Gson.

Java Gson toJson Example

The toJson() method serializes the specified object into its equivalent JSON representation.
package net.javaguides.gson;

import java.util.HashMap;
import java.util.Map;


public class GsonToJson {

    public static void main(String[] args) {

        Map < Integer, String > colours = new HashMap < > ();
        colours.put(1, "blue");
        colours.put(2, "yellow");
        colours.put(3, "green");
        colours.put(4, "red");

        Gson gson = new Gson();

        String output = gson.toJson(colours);