eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

In this tutorial, we’ll explore how to manage polymorphism with Gson. We’ll also explore some techniques for handling serialization and deserialization in polymorphic ways.

2. Polymorphism in JSON

Polymorphism in Java is well understood. We have a class hierarchy such that, when appropriate, we can treat different but related types the same in certain ways.

For example, we might have some definitions of various 2D shapes. Different shapes are defined in different ways, but they all have some common features — they can all calculate an area, for example.

As such, we could define some polymorphic classes for defining some shapes as:

interface Shape {
    double getArea();
}

class Circle implements Shape {
    private final double radius;
    private final double area;

    Circle(double radius) {
        this.radius = radius;
        this.area = Math.PI * radius * radius;
    }

    @Override
    public double getArea() {
        return area;
    }
}

class Square implements Shape {
    private final double side;
    private final double area;

    Square(double side) {
        this.side = side;
        this.area = side * side;
    }

    @Override
    public double getArea() {
        return area;
    }
}

Each of these shapes has its own concerns, but if we only care that each is a Shape and we can calculate its area, we can treat them all the same.

But how does this relate to JSON? We obviously can’t have functionality in a JSON document, but we can have data that overlaps, and we might want to have polymorphic classes represented in a reasonable way in our JSON.

For example, the above shapes might be represented:

[
    {
        "shape": "circle",
        "radius": 4,
        "area": 50.26548245743669
    }, {
        "shape": "square",
        "side": 5,
        "area": 25
    }
]

If we want to treat these simply as Shape instances, we already have the area available to us. However, if we want to know exactly what shapes they are, then we can identify this and extract extra information from them.

3. Using a Wrapper Object

The easiest way to solve this is to use a wrapper object and different fields for each of our types:

class Wrapper {
    private final Circle circle;
    private final Square square;

    Wrapper(Circle circle) {
        this.circle = circle;
        this.square = null;
    }

    Wrapper(Square square) {
        this.square = square;
        this.circle = null;
    }
}

Using something like this, our JSON will then look like:

[
    {
        "circle": {
            "radius": 4,
            "area": 50.26548245743669
        }
    }, {
        "square": {
            "side": 5,
            "area": 25
        }
    }
]

This isn’t technically polymorphic, and it does mean that the JSON is a different shape from what we had seen earlier, but it’s very easy to implement. In particular, we only need to write our wrapper type, and Gson will automatically do everything for us:

List<Wrapper> shapes = Arrays.asList(
    new Wrapper(new Circle(4d)),
    new Wrapper(new Square(5d))
);

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

Deserializing this also works exactly as we’d expect:

Gson gson = new Gson();

Type collectionType = new TypeToken<List<Wrapper>>(){}.getType();
List<Wrapper> shapes = gson.fromJson(json, collectionType);

Note that we need to use a TypeToken here because we’re deserializing to a generic list. This has nothing to do with our wrapper type and polymorphic structures.

However, this does mean that our Wrapper type needs to support every possible subtype. Adding new ones means a bit more work to achieve our desired end result.

4. Adding Type Field to Object

If we’re only interested in serializing our objects, we can simply add a field to them to indicate the type:

public class Square implements Shape {
    private final String type = "square"; // Added field
    private final double side;
    private final double area;

    public Square(double side) {
        this.side = side;
        this.area = side * side;
    }
}

Doing this will cause this new type field to appear in the serialized JSON, allowing clients to know which type each of the shapes is:

{
    "type": "square",
    "radius": 5,
    "area": 25
}

This is now closer to what we saw earlier. However, we can’t easily deserialize this JSON using this technique, so it’s only really viable in cases where we don’t need to do this.

5. Custom Type Adapter

The final way that we’re going to explore is by writing a custom type adapter. This is some code that we can contribute to the Gson instance that will then handle serializing and deserializing our types for us.

5.1. Custom Serializer

The first thing that we want to achieve is to be able to serialize our types correctly. This means serializing them with all of the standard logic but then adding an additional type field indicating the type of the object.

We achieve this by writing a custom implementation of JsonSerializer for our types:

public class ShapeTypeAdapter implements JsonSerializer<Shape> {
    @Override
    public JsonElement serialize(Shape shape, Type type, JsonSerializationContext context) {
        JsonElement elem = new Gson().toJsonTree(shape);
        elem.getAsJsonObject().addProperty("type", shape.getClass().getName());
        return elem;
    }
}

Note that we need to use a new Gson instance to serialize the value itself. If we reused the original instance – via the JsonSerializationContext – then we’d end up in an infinite loop where the serializer keeps calling itself.

Here, we’re using the full class name as our type, but we can equally use anything that we want to support this. We just need some way to uniquely convert between this string and the class name.

Using this, the resulting JSON will be:

[
    {
        "radius": 4,
        "area": 50.26548245743669,
        "type": "com.baeldung.gson.polymorphic.TypeAdapterUnitTest$Circle"
    },
    {
        "side": 5,
        "area": 25,
        "type": "com.baeldung.gson.polymorphic.TypeAdapterUnitTest$Square"
    }
]

5.2. Custom Deserializer

Now that we can serialize our types into JSON, we need to be able to deserialize them as well. This means understanding the type field and then using that to deserialize it into the correct class.

We achieve this by writing a custom implementation of JsonDeserializer for our types:

public class ShapeTypeAdapter implements JsonDeserializer<Shape> {
    @Override
    public Shape deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String typeName = jsonObject.get("type").getAsString();

        try {
            Class<? extends Shape> cls = (Class<? extends Shape>) Class.forName(typeName);
            return new Gson().fromJson(json, cls);
        } catch (ClassNotFoundException e) {
            throw new JsonParseException(e);
        }
    }
}

We can implement both our serializer and deserializer within the same class by simply implementing both interfaces. This helps keep the logic together so that we know that the two are compatible with each other.

As before, we need to use a new Gson instance to actually do the deserializing. Otherwise, we’ll end up in an infinite loop.

5.3. Wiring in the Type Adapter

Now that we’ve got a type adapter that can be used to serialize and deserialize our polymorphic types, we need to be able to use it. This means creating a Gson instance that has it wired in:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeHierarchyAdapter(Shape.class, new ShapeTypeAdapter());
Gson gson = builder.create();

We wire it in using the registerTypeHierarchyAdapter call since this means that it will be used for our Shape class and anything that implements it. This will then cause this Gson instance to use this adapter whenever it attempts to serialize anything implementing our Shape interface into JSON or whenever we attempt to deserialize JSON into anything that implements the Shape interface:

List<Shape> shapes = List.of(new Circle(4d), new Square(5d));

String json = gson.toJson(shapes);

Type collectionType = new TypeToken<List<Shape>>(){}.getType();
List<Shape> result = gson.fromJson(json, collectionType);

assertEquals(shapes, result);

6. Summary

Here, we’ve seen a few techniques for managing polymorphic types with Gson, both serializing them to JSON and deserializing them back from JSON.

Next time you’re working with JSON and polymorphic types, why not try some of them out?

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)