Convert Java Object to JSON using GSON

In this article, we will create an example to converting or serializing Java object to JSON representation using the GSON library.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. In this example, we will show you how you can serialize Java object to JSON using GSON.

GSON Maven Dependency

To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
      <scope>compile</scope>
    </dependency>
</dependencies>

Student POJO Class - Object to be Serialized

Let's create a Student class which has one to many relationships with Phone class. Let's create both Student and Phone class and we will seriliaze it to JSON representation using GSON.
class Student {

    private long studentId;
    private String studentName;
    private Set < Phone > studentPhoneNumbers = new HashSet < Phone > (0);

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Set < Phone > getStudentPhoneNumbers() {
        return studentPhoneNumbers;
    }

    public void setStudentPhoneNumbers(Set < Phone > studentPhoneNumbers) {
        this.studentPhoneNumbers = studentPhoneNumbers;
    }

    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentPhoneNumbers=" +
            studentPhoneNumbers + "]";
    }

}

class Phone {

    private long phoneId;
    private String phoneType;
    private String phoneNumber;

    public Phone() {}

    public Phone(String phoneType, String phoneNumber) {
        this.phoneType = phoneType;
        this.phoneNumber = phoneNumber;
    }

    public long getPhoneId() {
        return phoneId;
    }

    public void setPhoneId(long phoneId) {
        this.phoneId = phoneId;
    }

    public String getPhoneType() {
        return phoneType;
    }

    public void setPhoneType(String phoneType) {
        this.phoneType = phoneType;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Serialize or Convert Java Object to JSON using GSON

Good to know below points while converting Java Object to JSON using GSON:
  • You can not serialize objects with circular references since that will result in infinite recursion.
  • Google GSON supports pre-existing objects. This means that we do not need to annotate our classes with any special marker annotations.
  • Transient fields are by default ignored when serializing or deserializing.
  • While serialization, a null field is skipped from the output.
  • While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null.
  • Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization.
package net.javaguides.gson;

import java.util.HashSet;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class GSONComplexObjectExample {
    public static void main(String[] args) {
        serializeStudentObject();
    }

    private static void serializeStudentObject() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Student student = createStudent();
        String jsonStr = gson.toJson(student);
        System.out.println(jsonStr);
    }

    private static Student createStudent() {
        Student student = new Student();
        student.setStudentId(1000);
        student.setStudentName("Ramesh");
        Set < Phone > phones = new HashSet < Phone > ();
        Phone phone = new Phone();
        phone.setPhoneId(100);
        phone.setPhoneNumber("1234567890");
        phone.setPhoneType("Mobile Phone");
        phones.add(phone);

        Phone phone1 = new Phone();
        phone1.setPhoneId(101);
        phone1.setPhoneNumber("2222 3333 44");
        phone1.setPhoneType("Landline Phone");
        phones.add(phone1);

        student.setStudentPhoneNumbers(phones);
        return student;
    }
}
Output:
{
  "studentId": 1000,
  "studentName": "Ramesh",
  "studentPhoneNumbers": [
    {
      "phoneId": 100,
      "phoneType": "Mobile Phone",
      "phoneNumber": "1234567890"
    },
    {
      "phoneId": 101,
      "phoneType": "Landline Phone",
      "phoneNumber": "2222 3333 44"
    }
  ]
}

Complete Example for Reference

package net.javaguides.gson;

import java.util.HashSet;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class GSONComplexObjectExample {
    public static void main(String[] args) {
        serializeStudentObject();
    }

    private static void serializeStudentObject() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Student student = createStudent();
        String jsonStr = gson.toJson(student);
        System.out.println(jsonStr);
    }

    private static Student createStudent() {
        Student student = new Student();
        student.setStudentId(1000);
        student.setStudentName("Ramesh");
        Set < Phone > phones = new HashSet < Phone > ();
        Phone phone = new Phone();
        phone.setPhoneId(100);
        phone.setPhoneNumber("1234567890");
        phone.setPhoneType("Mobile Phone");
        phones.add(phone);

        Phone phone1 = new Phone();
        phone1.setPhoneId(101);
        phone1.setPhoneNumber("2222 3333 44");
        phone1.setPhoneType("Landline Phone");
        phones.add(phone1);

        student.setStudentPhoneNumbers(phones);
        return student;
    }
}

class Student {

    private long studentId;
    private String studentName;
    private Set < Phone > studentPhoneNumbers = new HashSet < Phone > (0);

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Set < Phone > getStudentPhoneNumbers() {
        return studentPhoneNumbers;
    }

    public void setStudentPhoneNumbers(Set < Phone > studentPhoneNumbers) {
        this.studentPhoneNumbers = studentPhoneNumbers;
    }

    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentPhoneNumbers=" +
            studentPhoneNumbers + "]";
    }

}

class Phone {

    private long phoneId;
    private String phoneType;
    private String phoneNumber;

    public Phone() {}

    public Phone(String phoneType, String phoneNumber) {
        this.phoneType = phoneType;
        this.phoneNumber = phoneNumber;
    }

    public long getPhoneId() {
        return phoneId;
    }

    public void setPhoneId(long phoneId) {
        this.phoneId = phoneId;
    }

    public String getPhoneType() {
        return phoneType;
    }

    public void setPhoneType(String phoneType) {
        this.phoneType = phoneType;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}
Output:
{
  "studentId": 1000,
  "studentName": "Ramesh",
  "studentPhoneNumbers": [
    {
      "phoneId": 100,
      "phoneType": "Mobile Phone",
      "phoneNumber": "1234567890"
    },
    {
      "phoneId": 101,
      "phoneType": "Landline Phone",
      "phoneNumber": "2222 3333 44"
    }
  ]
}

Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments