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.

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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

Google Gson is a useful and flexible library for JSON data binding in Java. In most cases, Gson can perform data binding to an existing class with no modification. However, certain class structures can cause issues that are difficult to debug.

One interesting and potentially confusing exception is an IllegalArgumentException that complains about multiple field definitions:

java.lang.IllegalArgumentException: Class <YourClass> declares multiple JSON fields named <yourField> ...

This can be particularly cryptic since the Java compiler doesn’t allow multiple fields in the same class to share a name. In this tutorial, we’ll discuss the causes of this exception and learn how to get around it.

2. Exception Causes

The potential causes for this exception relate to class structure or configuration that confuses the Gson parser when serializing (or de-serializing) a class.

2.1. @SerializedName Conflicts

Gson provides the @SerializedName annotation to allow manipulation of the field name in the serialized object. This is a useful feature, but it can lead to conflicts.

For example, let’s create a simple class, BasicStudent:

public class BasicStudent {
    private String name;
    private String major;
    @SerializedName("major")
    private String concentration;
    // General getters, setters, etc.
}

During serialization, Gson will attempt to use “major” for both major and concentration, leading to the IllegalArgumentException from above:

java.lang.IllegalArgumentException: Class BasicStudent declares multiple JSON fields named 'major';
conflict is caused by fields BasicStudent#major and BasicStudent#concentration

The exception message points to the problem fields and the issue can be addressed by simply changing or removing the annotation or renaming the field.

There are also other options for excluding fields in Gson, which we’ll discuss later in this tutorial.

First, let’s look at the other cause for this exception.

2.2. Class Inheritance Hierarchies

Class inheritance can also be a source of problems when serializing to JSON. To explore this issue, we’ll need to update our student data example.

Let’s define two classes, StudentV1 and StudentV2, which extends StudentV1 and adds an additional member variable:

public class StudentV1 {
    private String firstName;
    private String lastName;
    // General getters, setters, etc.
}
public class StudentV2 extends StudentV1 {
    private String firstName;
    private String lastName;
    private String major;
    // General getters, setters, etc.
}

Notably, StudentV2 not only extends StudentV1 but also defines its own set of variables, some of which duplicate those in StudentV1. While this isn’t best practice, it’s crucial to our example and something we may encounter in the real world when using a third-party library or legacy package.

Let’s create an instance of StudentV2 and attempt to serialize it. We can create a unit test to confirm that IllegalArgumentException is thrown:

@Test
public void givenLegacyClassWithMultipleFields_whenSerializingWithGson_thenIllegalArgumentExceptionIsThrown() {
    StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");

    Gson gson = new Gson();
    assertThatThrownBy(() -> gson.toJson(student))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessageContaining("declares multiple JSON fields named 'firstName'");
}

Similar to the @SerializedName conflicts above, Gson doesn’t know which field to use when encountering duplicate names in the class hierarchy.

3. Solutions

There are a few solutions to this issue, each with its own pros and cons that provide different levels of control over serialization.

3.1. Marking Fields as transient

The simplest way to control which fields are serialized is by using the transient field modifier. We can update BasicStudent from above:

public class BasicStudent {
    private String name;
    private transient String major;
    @SerializedName("major") 
    private String concentration; 

    // General getters, setters, etc. 
}

Let’s create a unit test to attempt serialization after this change:

@Test
public void givenBasicStudent_whenSerializingWithGson_thenTransientFieldNotSet() {
    BasicStudent student = new BasicStudent("Henry Winter", "Greek Studies", "Classical Greek Studies");

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

    BasicStudent deserialized = gson.fromJson(json, BasicStudent.class);
    assertThat(deserialized.getMajor()).isNull();
}

Serialization succeeds, and the major field value isn’t included in the de-serialized instance.

Though this is a simple solution, there are two downsides to this approach. Adding transient means the field will be excluded from all serialization, including basic Java serialization. This approach also assumes that BasicStudent can be modified, which may not always be the case.

3.2. Serialization With Gson’s @Expose Annotation

If the problem class can be modified and we want an approach scoped to only Gson serialization, we can make use of the @Expose annotation. This annotation informs Gson which fields should be exposed during serialization, de-serialization, or both.

We can update our StudentV2 instance to explicitly expose only its fields to Gson:

public class StudentV2 extends StudentV1 {
    @Expose
    private String firstName;
    @Expose 
    private String lastName; 
    @Expose
    private String major;

    // General getters, setters, etc. 
}

If we run the code again, nothing will change, and we’ll still see the exception. By default, Gson doesn’t change its behavior when encountering @Expose – we need to tell the parser what it should do.

Let’s update our unit test to use the GsonBuilder to create an instance of the parser that excludes fields without @Expose:

@Test
public void givenStudentV2_whenSerializingWithGsonExposeAnnotation_thenSerializes() {
    StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");

    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

    String json = gson.toJson(student);
    assertThat(gson.fromJson(json, StudentV2.class)).isEqualTo(student);
}

Serialization and de-serialization now succeed. @Expose has the benefit of still being a simple solution while only affecting Gson serialization (and only if we configure the parser to recognize it).

This approach still assumes we can edit the source code, however. It also doesn’t provide much flexibility – all fields that we care about need to be annotated, and the rest are excluded from both serialization and de-serialization.

3.3. Serialization With Gson’s ExclusionStrategy

Fortunately, Gson provides a solution when we can’t change the source class or we need more flexibility: the ExclusionStrategy.

This interface informs Gson of how to exclude fields during serialization or de-serialization and allows for more complex business logic. We can declare a simple ExclusionStrategy implementation:

public class StudentExclusionStrategy implements ExclusionStrategy {
    @Override
    public boolean shouldSkipField(FieldAttributes field) {
        return field.getDeclaringClass() == StudentV1.class;
    }

    @Override
    public boolean shouldSkipClass(Class<?> aClass) {
        return false;
    }
}

The ExclusionStrategy interface has two methods: shouldSkipField() provides granular control at the individual field level, and shouldSkipClass() controls if all fields of a certain type should be skipped. In our example above, we’re starting simple and skipping all fields from StudentV1.

Just as with @Expose, we need to tell Gson how to use this strategy. Let’s configure it in our test:

@Test
public void givenStudentV2_whenSerializingWithGsonExclusionStrategy_thenSerializes() {
    StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies");

    Gson gson = new GsonBuilder().setExclusionStrategies(new StudentExclusionStrategy()).create();

    assertThat(gson.fromJson(gson.toJson(student), StudentV2.class)).isEqualTo(student);
}

It’s worth noting that we’re configuring the parser with setExclusionStrategies() – this means our strategy is used for both serialization and de-serialization.

If we wanted more flexibility of when the ExclusionStrategy is applied, we could configure the parser differently:

// Only exclude during serialization
Gson gson = new GsonBuilder().addSerializationExclusionStrategy(new StudentExclusionStrategy()).create();

// Only exclude during de-serialization
Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(new StudentExclusionStrategy()).create();

This approach is slightly more complex than our other two solutions: we needed to declare a new class and think more about what makes a field important to include. We kept the business logic in our ExclusionStrategy fairly simple for this example, but the upside of this approach is richer and more robust field exclusion. Finally, we didn’t need to change the code inside StudentV2 or StudentV1.

4. Conclusion

In this article, we discussed the causes for a tricky yet ultimately fixable IllegalArgumentException we can encounter when using Gson.

We found that there are a variety of solutions we can implement based on our needs for simplicity, granularity, and flexibility.

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)