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 https://www.javaguides.net/p/google-gson-tutorial.html.

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

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

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

import com.google.gson.Gson;

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);

        System.out.println(output);
    }
}
Output:
{"1":"blue","2":"yellow","3":"green","4":"red"}

Reference


Comments