Deserialization – How to Create JSON Object to Java Object Using Gson API

In modern software development, working with JSON data is a common requirement. JSON (JavaScript Object Notation) is a lightweight data-interchange format, often used in RESTful web services, APIs, and data storage. When dealing with JSON in Java applications, it's crucial to convert (or deserialize) the JSON data into Java objects to manipulate it in a more structured way.

Gson is a powerful and easy-to-use library provided by Google for working with JSON in Java. In this post, we will explore how to use the Gson API to deserialize JSON into Java objects.

What is Deserialization?

Deserialization is the process of converting JSON data into Java objects. When a JSON object is received from an API or a file, it needs to be converted into a Java object so that the application can work with it.

For instance, if you have a JSON response from an API that contains information about a user, you can convert this JSON into a User Java object to access its properties programmatically.

Setting Up Gson

To begin using Gson in your Java project, you need to include the Gson dependency in your project’s pom.xml file if you’re using Maven.

<dependency>

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

    <artifactId>gson</artifactId>

    <version>2.8.8</version> <!-- or the latest version -->

</dependency>

If you’re using Gradle, you can add the following dependency:

implementation 'com.google.code.gson:gson:2.8.8' // or the latest version

Example: Deserializing JSON into a Java Object

Let's assume you have the following JSON representation of a User object:

{

    "id": 1,

    "name": "John Doe",

    "email": "john.doe@example.com"

}

And you want to convert this JSON into a User Java object.

Step 1: Create the Java Object (POJO)

Create a Java class User that reflects the structure of the JSON.

public class User {

    private int id;

    private String name;

    private String email;


    // Getters and Setters

    public int getId() {

        return id;

    }


    public void setId(int id) {

        this.id = id;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public String getEmail() {

        return email;

    }


    public void setEmail(String email) {

        this.email = email;

    }


    @Override

    public String toString() {

        return "User{id=" + id + ", name='" + name + "', email='" + email + "'}";

    }

}

Step 2: Deserialize JSON into Java Object Using Gson

Now that we have the User class, we can use the Gson library to deserialize the JSON string into a User object.

Here is the code to do that:

import com.google.gson.Gson;


public class GsonExample {

    public static void main(String[] args) {

        // JSON string representation of the User object

        String json = "{\"id\":1, \"name\":\"John Doe\", \"email\":\"john.doe@example.com\"}";


        // Create a Gson instance

        Gson gson = new Gson();


        // Deserialize JSON string into a User object

        User user = gson.fromJson(json, User.class);


        // Print the deserialized User object

        System.out.println(user);

    }

}

Output:

User{id=1, name='John Doe', email='john.doe@example.com'}

Explanation

  • Gson Instance: We create an instance of the Gson class to handle the deserialization.
  • fromJson() Method: The fromJson() method is used to deserialize the JSON string into a Java object. It takes two parameters: the JSON string and the class type (User.class).
  • User Object: After deserialization, the User object is populated with data from the JSON string.

Handling Nested JSON

In real-world applications, JSON data is often more complex and may contain nested objects or arrays. Gson can handle such scenarios as well.

Consider the following JSON example where a User object contains an array of Address objects.

{

    "id": 1,

    "name": "John Doe",

    "email": "john.doe@example.com",

    "addresses": [

        {

            "street": "123 Main St",

            "city": "Springfield",

            "state": "IL"

        },

        {

            "street": "456 Elm St",

            "city": "Chicago",

            "state": "IL"

        }

    ]

}

To deserialize this, you need to create an Address class and update the User class to include a list of Address objects.

Step 1: Create the Address Class

public class Address {
    private String street;
    private String city;
    private String state;

    // 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 String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                ", state='" + state + '\'' +
                '}';
    }
}

Step 2: Update the User Class

Modify the User class to include a list of Address objects.

import java.util.List;


public class User {

    private int id;

    private String name;

    private String email;

    private List<Address> addresses;


    // Getters and Setters

    public int getId() {

        return id;

    }


    public void setId(int id) {

        this.id = id;

    }


    public String getName() {

        return name;

    }


    public void setName(String name) {

        this.name = name;

    }


    public String getEmail() {

        return email;

    }


    public void setEmail(String email) {

        this.email = email;

    }


    public List<Address> getAddresses() {

        return addresses;

    }


    public void setAddresses(List<Address> addresses) {

        this.addresses = addresses;

    }


    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", name='" + name + '\'' +

                ", email='" + email + '\'' +

                ", addresses=" + addresses +

                '}';

    }

}

Step 3: Deserialize Nested JSON

Now you can deserialize the JSON string that contains a list of addresses:

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;


public class GsonExample {

    public static void main(String[] args) {

        // JSON string with nested addresses

        String json = "{\"id\":1, \"name\":\"John Doe\", \"email\":\"john.doe@example.com\", \"addresses\":[{\"street\":\"123 Main St\", \"city\":\"Springfield\", \"state\":\"IL\"}, {\"street\":\"456 Elm St\", \"city\":\"Chicago\", \"state\":\"IL\"}]}";


        // Create a Gson instance

        Gson gson = new Gson();


        // Deserialize JSON into User object

        User user = gson.fromJson(json, User.class);


        // Print the deserialized User object

        System.out.println(user);

    }

}

Output:

User{id=1, name='John Doe', email='john.doe@example.com', addresses=[Address{street='123 Main St', city='Springfield', state='IL'}, Address{street='456 Elm St', city='Chicago', state='IL'}]}

Followers