Java Gson toJson() Example

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.
The toJson() method serializes the specified object into its equivalent JSON representation.
Check out top GSON tutorial at Google GSON Tutorial.

Java Gson Maven dependency

This is a Maven dependency for Gson:

Java Gson toJson() Example

In the example, we serialize a map into JSON with toJSon() method.
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");
        Gson gson = new Gson();
        String output = gson.toJson(colours);
This is the output of the example.