Serialization: How to Convert Java Object to JSON Object Using Gson API

Serialization is the process of converting an object into a format that can be easily stored or transmitted. In Java, this typically means converting a Java object to a JSON format. JSON (JavaScript Object Notation) is a lightweight data interchange format, widely used for data exchange in web services and APIs.

In this blog post, we will explore how to use the Gson library to serialize Java objects into JSON objects.

What is Gson?

Gson is a Java library developed by Google that can be used to convert Java objects into JSON and vice versa. It provides simple methods for converting Java objects into JSON and deserializing JSON back into Java objects.

Why Use Gson?

  • Simple to Use: Gson makes it easy to convert Java objects to JSON and vice versa, with just a few lines of code.
  • Lightweight: It's a small library that doesn’t add much overhead to your project.
  • Flexible: It handles complex data types, including collections, generics, and nested objects.
  • Customizable: Gson allows you to configure how Java objects are serialized and deserialized.

Steps to Serialize Java Object to JSON Using Gson API

To demonstrate how to serialize Java objects into JSON using Gson, follow these steps:

Step 1: Add Gson to Your Project

If you're using Maven, you can add the Gson dependency to your pom.xml:

<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.8.8</version>

</dependency>

If you're using Gradle, add the following to your build.gradle file:

implementation 'com.google.code.gson:gson:2.8.8'

Step 2: Create a Java Class

Let’s create a simple Java class that we want to serialize into JSON.

public class Employee {

    private String name;

    private int age;

    private String department;


    // Constructor

    public Employee(String name, int age, String department) {

        this.name = name;

        this.age = age;

        this.department = department;

    }


    // Getters and Setters

    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public int getAge() {

        return age;

    }


    public void setAge(int age) {

        this.age = age;

    }


    public String getDepartment() {

        return department;

    }


    public void setDepartment(String department) {

        this.department = department;

    }

}

Step 3: Serialize Java Object to JSON

To serialize the Employee object into JSON format, we will use the Gson class provided by the Gson library.

Here’s the code to serialize the object:

import com.google.gson.Gson;


public class SerializationExample {

    public static void main(String[] args) {

        // Create an Employee object

        Employee employee = new Employee("John Doe", 30, "Engineering");


        // Create a Gson object

        Gson gson = new Gson();


        // Serialize the Employee object to JSON

        String json = gson.toJson(employee);


        // Print the JSON

        System.out.println(json);

    }

}

Output:

{"name":"John Doe","age":30,"department":"Engineering"}

In the example above, we created an Employee object and used the toJson() method from the Gson class to serialize it into a JSON string.

Step 4: Handle Nested Objects

Gson can also handle nested objects. Let’s modify the Employee class to include an Address class as a nested object.

public class Address {

    private String street;

    private String city;


    // Constructor

    public Address(String street, String city) {

        this.street = street;

        this.city = city;

    }


    // Getters and Setters

    public String getStreet() {

        return street;

    }


    public void setStreet(String street) {

        this.street = street;

    }


    public String getCity() {

        return city;

    }


    public void setCity(String city) {

        this.city = city;

    }

}


public class Employee {

    private String name;

    private int age;

    private String department;

    private Address address;  // Nested object


    // Constructor

    public Employee(String name, int age, String department, Address address) {

        this.name = name;

        this.age = age;

        this.department = department;

        this.address = address;

    }


    // Getters and Setters

    // ...

}

Now, let's serialize the Employee object with a nested Address object:

public class SerializationExample {
    public static void main(String[] args) {
        // Create an Address object
        Address address = new Address("123 Main St", "New York");

        // Create an Employee object with the Address object
        Employee employee = new Employee("John Doe", 30, "Engineering", address);

        // Create a Gson object
        Gson gson = new Gson();

        // Serialize the Employee object with Address to JSON
        String json = gson.toJson(employee);

        // Print the JSON
        System.out.println(json);
    }
}

Output:

{
  "name": "John Doe",
  "age": 30,
  "department": "Engineering",
  "address": {
    "street": "123 Main St",
    "city": "New York"
  }
}

Step 5: Customizing Serialization

Gson allows for customizing the serialization process. For example, you can use annotations like @Expose to control which fields are included in the JSON.

import com.google.gson.annotations.Expose;


public class Employee {

    @Expose

    private String name;

    

    @Expose

    private int age;

    

    private String department;  // Not serialized


    // Constructor and Getters/Setters

}

Then, when serializing, you can create a Gson object that only includes fields annotated with @Expose:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(employee);

Followers