DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Proper Java Exception Handling
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Implementing Infinite Scroll in jOOQ

Trending

  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  1. DZone
  2. Coding
  3. Frameworks
  4. JSON Handling With GSON in Java With OOP Essence

JSON Handling With GSON in Java With OOP Essence

This guide will introduce you to GSON with practical examples and explore how OOP principles play a crucial role in the process.

By 
Reza Ganji user avatar
Reza Ganji
DZone Core CORE ·
Jan. 04, 24 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
11.0K Views

Join the DZone community and get the full member experience.

Join For Free

Managing JSON data in the world of Java development can be a challenging task. However, GSON, a powerful library developed by Google, can simplify the conversion between Java objects and JSON strings. This article will guide you through the basics of GSON, using practical examples, and show how Object-Oriented Programming (OOP) principles play a crucial role in this process.

What Is GSON? 

GSON is a Java library that simplifies the process of converting Java objects to JSON and vice versa. It stands for "Google's JSON" and provides developers with a seamless integration between their Java objects and JSON data. This means manual parsing and formatting are not required, making working with JSON data easier and more efficient.

Getting Started

To utilize the GSON library in your project, you need to add it to your project's dependencies. GSON is a popular Java library for serializing and deserializing Java objects to JSON and vice versa. It provides a simple and efficient way to convert JSON strings to Java objects and vice versa.

If you're using Maven, you can easily include GSON by adding the following dependency to your project's pom.xml file:

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


Once you've added this dependency, you can use GSON in your code.

Serialization: Java Object to JSON 

Consider a simple `Person` class:

Java
 
public class Person {
    private String name;
    private int age;
    // getters and setters
}


To convert objects to JSON, we can use the following code to serialize them:

Java
 
import com.google.gson.Gson;
public class SerializationExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setAge(20);

        Gson gson = new Gson();
        String json = gson.toJson(person);

        System.out.println(json);
    }
}


The output will look like this:

Shell
 
{"name":"John","age":30}


Deserialization: JSON to Java Object

In GSON, a reverse process allows you to convert JSON back into an object. This can be useful if you have previously converted an object into a JSON format and now need to retrieve the original object. The process involves using the GSON library to deserialize the JSON string and convert it into an object. This can be done using the fromJson() method, which takes in the JSON string and the object's class to be created. Once the JSON string has been deserialized, a new object will be created with the same properties as the original object:

Java
 
import com.google.gson.Gson;
public class DeserializationExample {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Jane\",\"age\":25,\"studentId\":\"S67890\"}";

        Gson gson = new Gson();
        Student student = gson.fromJson(jsonString, Student.class);

        System.out.println("Name: " + student.getName());
        System.out.println("Age: " + student.getAge());
        System.out.println("Student ID: " + student.getStudentId());
    }
}


The above code code converts the JSON string back into a `Student` object.

GSON Annotations

GSON provides various annotations to customize the serialization and deserialization processes:

@SerializedName

 Allows you to specify a custom name for the JSON key. For example: 

Java
 
public class Person {
    @SerializedName("full_name")
    private String name;
    private int age;

    // getters and setters
}

In this example, the `@SerializedName` annotation changes the JSON key to "full_name" instead of "name."


@Expose

 Controls field inclusion and exclusion during serialization and deserialization. For example:

Java
 
import com.google.gson.annotations.Expose;

public class Person {
    @Expose
    private String name;
    @Expose(serialize = false)
    private int age;

    // getters and setters
}

The `age` field will be excluded during serialization due to `serialize = false.`

@Since and @Until

Specify version information for fields. For example: 
Java
 
mport com.google.gson.annotations.Since;
import com.google.gson.annotations.Until;

public class Product {
    @Since(1.0)
    private String name;
    @Until(2.0)
    private double price;

    // getters and setters
}

In this case, the `name` field is included in versions 1.0 and above, while the `price` field is included until version 2.0.

Object-Oriented Programming in Gson

Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of "objects." In this paradigm, objects are the basic building blocks of software development. An object is an instance of a class, which is a blueprint that defines the structure and behavior of objects.

The four main principles of OOP are encapsulation, inheritance, polymorphism, and abstraction. Encapsulation is the practice of hiding the implementation details of an object from the outside world. Inheritance is the ability of objects to inherit properties and methods from their parent class. Polymorphism is the ability of objects to take on multiple forms, allowing different objects to be treated as if they were the same. Abstraction is the process of focusing on essential features of an object while ignoring its non-essential details.

In addition to these principles, object-oriented programming concepts can be applied to objects in the serialization and deserialization process. Serialization is the process of transforming an object into a format that can be easily stored or transmitted. Deserialization is the process of transforming a serialized object back into its original form. When working with GSON, the principles of OOP can be used to ensure that serialized and deserialized objects are consistent with their original form.

Let's dive into polymorphism and inheritance in GSON:

Inheritance With GSON in Java

Inheritance is a fundamental concept in Object-Oriented Programming. It allows a subclass or child class to inherit attributes and behaviors from a superclass or parent class. When working with GSON in Java, it is essential to understand how inheritance can be managed during serialization and deserialization. 

For instance, suppose we have a base class called Vehicle and two subclasses, Car and Motorcycle. In that case, we need to explore how GSON handles the serialization and deserialization of these classes:

Java
 

class Vehicle {
    private String type;

    // Constructors, getters, setters, and other methods omitted for brevity

    @Override
    public String toString() {
        return "Vehicle{" +
                "type='" + type + '\'' +
                '}';
    }
}

class Car extends Vehicle {
    private int numberOfDoors;

    // Constructors, getters, setters, and other methods omitted for brevity

    @Override
    public String toString() {
        return "Car{" +
                "type='" + getType() + '\'' +
                ", numberOfDoors=" + numberOfDoors +
                '}';
    }
}

class Motorcycle extends Vehicle {
    private boolean hasSidecar;

    // Constructors, getters, setters, and other methods omitted for brevity

    @Override
    public String toString() {
        return "Motorcycle{" +
                "type='" + getType() + '\'' +
                ", hasSidecar=" + hasSidecar +
                '}';
    }
}

public class InheritanceWithGsonExample {
    public static void main(String[] args) {
        // Creating instances of Car and Motorcycle
        Car car = new Car();
        car.setType("Car");
        car.setNumberOfDoors(4);

        Motorcycle motorcycle = new Motorcycle();
        motorcycle.setType("Motorcycle");
        motorcycle.setHasSidecar(true);

        // Using Gson for serialization
        Gson gson = new Gson();
        String carJson = gson.toJson(car);
        String motorcycleJson = gson.toJson(motorcycle);

        System.out.println("Car JSON: " + carJson);
        System.out.println("Motorcycle JSON: " + motorcycleJson);

        // Using Gson for deserialization
        Car deserializedCar = gson.fromJson(carJson, Car.class);
        Motorcycle deserializedMotorcycle = gson.fromJson(motorcycleJson, Motorcycle.class);

        System.out.println("Deserialized Car: " + deserializedCar);
        System.out.println("Deserialized Motorcycle: " + deserializedMotorcycle);
    }
}


The code above demonstrates a class hierarchy with inheritance and serialization/deserialization using GSON. The Vehicle class is the base class with a common attribute called "type". The Car and Motorcycle classes are subclasses of Vehicles that inherit the "type" attribute and have additional attributes specific to each type of vehicle. The InheritanceWithGsonExample class showcases the serialization and deserialization of Car and Motorcycle objects using Gson. During serialization, GSON automatically includes fields from the superclass, and during deserialization, it correctly reconstructs the class hierarchy. As a result, the output JSON will contain both the attributes from the subclass and its superclass.

Polymorphism With GSON in Java

Polymorphism is a crucial concept in Object-Oriented Programming (OOP). It enables objects of different types to be treated as if they were objects of a shared type. GSON utilizes the `@JsonSubTypes` annotation to support polymorphism and the `RuntimeTypeAdapterFactory` class. 

To better understand this concept, let's consider an example with an interface called `Shape,` which includes two implementing classes, `Circle` and `Rectangle`:

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

interface Shape {
    double calculateArea();
}

class Circle implements Shape {
    private double radius;

    // Constructors, getters, setters, and other methods omitted for brevity

    @Override
    public double calculateArea() {
        return Math.PI * Math.pow(radius, 2);
    }
}

class Rectangle implements Shape {
    private double length;
    private double width;

    // Constructors, getters, setters, and other methods omitted for brevity

    @Override
    public double calculateArea() {
        return length * width;
    }
}

public class PolymorphismWithGsonExample {
    public static void main(String[] args) {
        // Creating instances of Circle and Rectangle
        Circle circle = new Circle();
        circle.setRadius(5);

        Rectangle rectangle = new Rectangle();
        rectangle.setLength(4);
        rectangle.setWidth(6);

        // Using Gson with RuntimeTypeAdapterFactory for polymorphism
        Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(RuntimeTypeAdapterFactory
                        .of(Shape.class, "type")
                        .registerSubtype(Circle.class, "circle")
                        .registerSubtype(Rectangle.class, "rectangle"))
                .create();

        // Serialization
        String circleJson = gson.toJson(circle, Shape.class);
        String rectangleJson = gson.toJson(rectangle, Shape.class);

        System.out.println("Circle JSON: " + circleJson);
        System.out.println("Rectangle JSON: " + rectangleJson);

        // Deserialization
        Shape deserializedCircle = gson.fromJson(circleJson, Shape.class);
        Shape deserializedRectangle = gson.fromJson(rectangleJson, Shape.class);

        System.out.println("Deserialized Circle Area: " + deserializedCircle.calculateArea());
        System.out.println("Deserialized Rectangle Area: " + deserializedRectangle.calculateArea());
    }
}


The provided code showcases the implementation of the Shape Interface, which serves as a common type for various shapes, featuring a method named calculateArea(). The code also includes the Circle Class and Rectangle Class, which implement the Shape interface and provide their specific implementations of the calculateArea() method. Additionally, the PolymorphismWithGsonExample Class demonstrates how to serialize and deserialize Circle and Rectangle objects using GSON with a RuntimeTypeAdapterFactory. The RuntimeTypeAdapterFactory allows GSON to include type information in the JSON representation, ensuring that objects of different types that implement the common Shape interface can be deserialized correctly.

Conclusion

GSON is a popular Java library that provides easy-to-use APIs to serialize and deserialize Java objects to and from JSON (JavaScript Object Notation) format. One of the key features of GSON is its ability to handle inheritance and polymorphism seamlessly in Java. In object-oriented programming, inheritance is a mechanism that allows a new class to be based on an existing class, inheriting its properties and methods. Polymorphism, however, will enable objects of different types to be treated as if they were of the same type based on their common interface or superclass.

When working with object-oriented code that involves class hierarchies and interface implementations, GSON can be a powerful tool. It can automatically handle the serialization and deserialization of objects with a common superclass or interface. This means you don't need to write any custom code to handle the serialization and deserialization of objects with different types that share common properties.

For example, suppose you have a class hierarchy that consists of a base class and several derived classes. Each derived class has additional properties and methods that are specific to that class. With GSON, you can serialize and deserialize objects of any of these classes, and GSON will automatically handle the details of the inheritance and polymorphism for you.

In conclusion, GSON is a valuable tool for working with object-oriented code that involves inheritance and polymorphism. It can save time and effort when serializing and deserializing objects with different types that share common properties.

Gson JSON Object-oriented programming Java (programming language) Data Types Object type (object-oriented programming)

Opinions expressed by DZone contributors are their own.

Related

  • Test Parameterization With JUnit 5.7: A Deep Dive Into @EnumSource
  • Proper Java Exception Handling
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Implementing Infinite Scroll in jOOQ

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!