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:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java Gson toJson() Example

In the example, we serialize a map into JSON with toJSon() method.
import com.google.gson.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");
        
        Gson gson = new Gson();
        
        String output = gson.toJson(colours);
        
        System.out.println(output);
    }
}
Output:
{"1":"blue","2":"yellow","3":"green"}
This is the output of the example.

Comments