Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

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