Serializes Java object into JSON string using Gson.toJson() with Gson

Tags: JSON gson

Java Code Examples for com.google.gson.Gson.toJson()

This method to serializes the Java object into JSON string.

Adding Gson dependency into your project

Using Gradle

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

Using Maven

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

How to use com.google.gson.Gson.toJson()

package simplesolution.dev;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GsonToJsonExamples {
    public static void main(String... args) {
        List<Map<String, String>> data = new ArrayList<>();
        Map<String, String> item1 = new HashMap<>();
        item1.put("name", "Sample JSON Serialization");
        item1.put("url", "https://simplesolution.dev");
        data.add(item1);

        Map<String, String> item2 = new HashMap<>();
        item2.put("name", "Java Tutorials");
        item2.put("url", "https://simplesolution.dev/java");
        data.add(item2);

        Gson gson = new Gson();
        String jsonStringFromObject = gson.toJson(data);
        System.out.println("JSON String from Object: " + jsonStringFromObject);
    }
}

Happy Coding 😊