Skip to content

Java Gson toJson() Example

Ramesh Fadatare edited this page Jul 14, 2019 · 2 revisions

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.

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() Method

The toJson() method serializes the specified object into its equivalent JSON representation.

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.

Clone this wiki locally