Guide to GSON Library in Java

Introduction

GSON is a popular Java library developed by Google for converting Java objects to JSON and vice versa. It is lightweight, easy to use, and highly customizable. GSON can handle a wide range of use cases, from simple serialization/deserialization to complex scenarios involving custom types and adapters.

Installation

To use GSON, add the following dependency to your pom.xml if you're using Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.0</version> <!-- or the latest version -->
</dependency>

For Gradle:

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

Basic Usage

Gson Object

The Gson class is the primary class used for converting Java objects to JSON and vice versa.

Example: Serialize Java Object to JSON

import com.google.gson.Gson;

public class SerializeExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        User user = new User("Arjun", 28);
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }
}

Output

JSON String: {"name":"Arjun","age":28}

Example: Deserialize JSON to Java Object

import com.google.gson.Gson;

public class DeserializeExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"name\":\"Arjun\",\"age\":28}";
        User user = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + user.getName() + ", Age: " + user.getAge());
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }
}

Output

User: Arjun, Age: 28

Advanced Usage

Annotations

GSON provides various annotations to control the serialization and deserialization processes.

Example: @SerializedName

import com.google.gson.annotations.SerializedName;
import com.google.gson.Gson;

public class SerializedNameExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"full_name\":\"Aarti\",\"age\":25}";
        User user = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + user.getFullName() + ", Age: " + user.getAge());
    }

    static class User {
        @SerializedName("full_name")
        private String fullName;
        private int age;

        public User(String fullName, int age) {
            this.fullName = fullName;
            this.age = age;
        }

        // getters and setters
        public String getFullName() {
            return fullName;
        }

        public void setFullName(String fullName) {
            this.fullName = fullName;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

Output

User: Aarti, Age: 25

Example: @Expose

The @Expose annotation can be used to include or exclude fields during serialization and deserialization.

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

public class ExposeExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        User user = new User("Ravi", 40, "secret");
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        @Expose
        private String name;
        @Expose
        private int age;
        private String password;

        public User(String name, int age, String password) {
            this.name = name;
            this.age = age;
            this.password = password;
        }

        // 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 getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
}

Output

JSON String: {"name":"Ravi","age":40}

Custom Serializer and Deserializer

GSON allows you to create custom serializers and deserializers for complex data types.

Example: Custom Serializer

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

public class CustomSerializerExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserSerializer()).create();
        User user = new User("Priya", 35);
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }

    static class UserSerializer implements JsonSerializer<User> {
        @Override
        public JsonElement serialize(User user, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("user_name", user.getName());
            jsonObject.addProperty("user_age", user.getAge());
            return jsonObject;
        }
    }
}

Output

JSON String: {"user_name":"Priya","user_age":35}

Example: Custom Deserializer

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.io.IOException;

public class CustomDeserializerExample {
    public static void main(String[] args) throws IOException {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserDeserializer()).create();
        String jsonString = "{\"user_name\":\"Rahul\",\"user_age\":32}";
        User user = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + user.getName() + ", Age: " + user.getAge());
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }

    static class UserDeserializer implements JsonDeserializer<User> {
        @Override
        public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();
            String name = jsonObject.get("user_name").getAsString();
            int age = jsonObject.get("user_age").getAsInt();
            return new User(name, age);
        }
    }
}

Output

User: Rahul, Age: 32

Working with Collections

Example: Serialize and Deserialize a List

import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        List<User> users = List.of(new User("Amit", 30), new User("Sneha", 25));
        String jsonString = gson.toJson(users);




 System.out.println("JSON String: " + jsonString);

        Type userListType = new TypeToken<List<User>>() {}.getType();
        List<User> deserializedUsers = gson.fromJson(jsonString, userListType);
        deserializedUsers.forEach(user -> System.out.println("User: " + user.getName() + ", Age: " + user.getAge()));
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }
}

Output

JSON String: [{"name":"Amit","age":30},{"name":"Sneha","age":25}]
User: Amit, Age: 30
User: Sneha, Age: 25

Example: Serialize and Deserialize a Map

import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Map<String, Integer> map = Map.of("Ankit", 35, "Divya", 29);
        String jsonString = gson.toJson(map);
        System.out.println("JSON String: " + jsonString);

        Type mapType = new TypeToken<Map<String, Integer>>() {}.getType();
        Map<String, Integer> deserializedMap = gson.fromJson(jsonString, mapType);
        deserializedMap.forEach((name, age) -> System.out.println("Name: " + name + ", Age: " + age));
    }
}

Output

JSON String: {"Ankit":35,"Divya":29}
Name: Ankit, Age: 35
Name: Divya, Age: 29

Handling Dates

Example: Serialize and Deserialize Java Date

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

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

        DateHolder dateHolder = new DateHolder(new Date());
        String jsonString = gson.toJson(dateHolder);
        System.out.println("JSON String: " + jsonString);

        DateHolder deserializedDateHolder = gson.fromJson(jsonString, DateHolder.class);
        System.out.println("Date: " + new SimpleDateFormat("yyyy-MM-dd").format(deserializedDateHolder.getDate()));
    }

    static class DateHolder {
        private Date date;

        public DateHolder(Date date) {
            this.date = date;
        }

        // getters and setters
        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }
    }
}

Output

JSON String: {"date":"2024-05-17"}
Date: 2024-05-17

Customizing Gson

Example: Enabling Pretty Print

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

public class PrettyPrintExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        User user = new User("Manisha", 22);
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        // 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;
        }
    }
}

Output

JSON String: {
  "name": "Manisha",
  "age": 22
}

Let's learn more complex and nested examples using the GSON library.

Complex and Nested Examples

Example: Nested Objects

When dealing with nested objects, GSON can easily handle the serialization and deserialization process.

Serialize and Deserialize Nested Objects

import com.google.gson.Gson;

public class NestedObjectsExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Address address = new Address("123 Main St", "Mumbai", "400001");
        User user = new User("Ravi", 32, address);
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);

        User deserializedUser = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + deserializedUser.getName() + ", Age: " + deserializedUser.getAge());
        System.out.println("Address: " + deserializedUser.getAddress().getStreet() + ", " +
                deserializedUser.getAddress().getCity() + ", " + deserializedUser.getAddress().getZipCode());
    }

    static class User {
        private String name;
        private int age;
        private Address address;

        public User(String name, int age, Address address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        // 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 Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }
    }

    static class Address {
        private String street;
        private String city;
        private String zipCode;

        public Address(String street, String city, String zipCode) {
            this.street = street;
            this.city = city;
            this.zipCode = zipCode;
        }

        // 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 getZipCode() {
            return zipCode;
        }

        public void setZipCode(String zipCode) {
            this.zipCode = zipCode;
        }
    }
}

Output

JSON String: {"name":"Ravi","age":32,"address":{"street":"123 Main St","city":"Mumbai","zipCode":"400001"}}
User: Ravi, Age: 32
Address: 123 Main St, Mumbai, 400001

Example: Nested Collections

GSON can also handle nested collections such as lists within lists or maps within lists.

Serialize and Deserialize Nested Collections

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class NestedCollectionsExample {
    public static void main(String[] args) {
        Gson gson = new Gson();

        List<Map<String, List<String>>> nestedCollection = List.of(
                Map.of("group1", List.of("Rohit", "Priya")),
                Map.of("group2", List.of("Kiran", "Anjali"))
        );

        String jsonString = gson.toJson(nestedCollection);
        System.out.println("JSON String: " + jsonString);

        Type type = new TypeToken<List<Map<String, List<String>>>>() {}.getType();
        List<Map<String, List<String>>> deserializedCollection = gson.fromJson(jsonString, type);

        deserializedCollection.forEach(group -> {
            group.forEach((key, value) -> {
                System.out.println("Group: " + key + ", Members: " + value);
            });
        });
    }
}

Output

JSON String: [{"group1":["Rohit","Priya"]},{"group2":["Kiran","Anjali"]}]
Group: group1, Members: [Rohit, Priya]
Group: group2, Members: [Kiran, Anjali]

Example: Custom Nested Serialization and Deserialization

You can also create custom serializers and deserializers for nested objects.

Custom Nested Serializer

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

public class CustomNestedSerializerExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserSerializer()).create();
        Address address = new Address("456 Park Ave", "Delhi", "110001");
        User user = new User("Vikas", 29, address);
        String jsonString = gson.toJson(user);
        System.out.println("JSON String: " + jsonString);
    }

    static class User {
        private String name;
        private int age;
        private Address address;

        public User(String name, int age, Address address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        // 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 Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }
    }

    static class Address {
        private String street;
        private String city;
        private String zipCode;

        public Address(String street, String city, String zipCode) {
            this.street = street;
            this.city = city;
            this.zipCode = zipCode;
        }

        // 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 getZipCode() {
            return zipCode;
        }

        public void setZipCode(String zipCode) {
            this.zipCode = zipCode;
        }
    }

    static class UserSerializer implements JsonSerializer<User> {
        @Override
        public JsonElement serialize(User user, Type typeOfSrc, JsonSerializationContext context) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("user_name", user.getName());
            jsonObject.addProperty("user_age", user.getAge());

            JsonObject addressObject = new JsonObject();
            addressObject.addProperty("street", user.getAddress().getStreet());
            addressObject.addProperty("city", user.getAddress().getCity());
            addressObject.addProperty("zip_code", user.getAddress().getZipCode());

            jsonObject.add("user_address", addressObject);
            return jsonObject;
        }
    }
}

Output

JSON String: {"user_name":"Vikas","user_age":29,"user_address":{"street":"456 Park Ave","city":"Delhi","zip_code":"110001"}}

Custom Nested Deserializer

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;

public class CustomNestedDeserializerExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserDeserializer()).create();
        String jsonString = "{\"user_name\":\"Snehal\",\"user_age\":26,\"user_address\":{\"street\":\"789 Hill St\",\"city\":\"Pune\",\"zip_code\":\"411001\"}}";
        User user = gson.fromJson(jsonString, User.class);
        System.out.println("User: " + user.getName() + ", Age: " + user.getAge());
        System.out.println("Address: " + user.getAddress().getStreet() + ", " +
                user.getAddress().getCity() + ", " + user.getAddress().getZipCode());
    }

    static class User {
        private String name;
        private int age;
        private Address address;

        public User(String name, int age, Address address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        // 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 Address getAddress() {
            return address;
        }

        public void setAddress(Address address) {
            this.address = address;
        }
    }

    static class Address {
        private String street;
        private String city;
        private String zipCode;

        public Address(String street, String city, String zipCode) {
            this.street = street;
            this.city = city;
            this.zipCode = zipCode;
        }

        // 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 getZipCode() {
            return zipCode;
        }

        public void setZipCode(String zipCode) {
            this.zipCode = zipCode;
        }
    }

    static class UserDeserializer implements JsonDeserializer<User> {
        @Override
        public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();
            String name = jsonObject.get("user_name").getAsString();
            int age = jsonObject.get("user_age").getAsInt();

            JsonObject addressObject = jsonObject.getAsJsonObject("user_address");
            String street = addressObject.get("street").getAsString();
            String city = addressObject.get("city").getAsString();
            String zipCode = addressObject.get("zip_code").getAsString();

            Address address = new Address(street, city, zipCode);
            return new User(name, age, address);
        }
    }
}

Output

User: Snehal, Age: 26
Address: 789 Hill St, Pune, 411001

Conclusion

GSON is a powerful and flexible library for processing JSON in Java. This tutorial covered basic and advanced usage, including serialization and deserialization of simple and nested objects, handling collections, custom serialization and deserialization, and using annotations. By leveraging GSON, you can efficiently handle complex JSON data structures in your Java applications. For more detailed information and advanced features, refer to the official GSON documentation.

Comments