Streamlining Java Serialization with Lombok and Gson

Hatim Tachi
3 min readMar 3, 2024

--

In the realm of Java development, reducing boilerplate code and simplifying data serialization are crucial for creating efficient and maintainable applications. Lombok, with its suite of annotations, significantly cuts down on the verbosity of Java code. Meanwhile, Gson offers a powerful and flexible toolset for serializing and deserializing Java objects into JSON. By combining these two libraries, developers can achieve a cleaner, annotation-driven approach to handling Java objects, especially when it comes to customizing JSON output without implementing JsonSerializer. Let's dive into how we can leverage Lombok and Gson together, focusing on annotation-driven customization for JSON serialization.

Why Use Lombok and Gson?

Lombok streamlines Java development by automating the generation of boilerplate code through annotations. This includes getters, setters, constructors, and more, reducing the chance of error and making the codebase easier to read and maintain.

Gson, on the other hand, excels at converting Java objects into their JSON representation and vice versa, with minimal configuration. However, situations arise where the default serialization behavior isn’t quite what’s needed. This is where Gson’s ability to customize serialization through annotations becomes invaluable, allowing for precise control over the JSON output.

Setting Up Your Project

To use Lombok and Gson, ensure they are included in your project’s build path. For Maven projects, add the following dependencies to your pom.xml file:

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>

Leveraging Annotations for Custom Serialization

While Gson does not directly use annotations for custom field serialization in the same way Lombok does for reducing boilerplate code, you can use a combination of Gson’s @Expose annotation and Lombok's features to control your JSON output effectively.

Excluding Fields Without @Expose

Gson serializes all fields in a Java object by default. However, you can configure Gson to ignore fields not marked with the @Expose annotation:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
class User {
@Expose
private String username;
private transient String password; // Transient fields are skipped by default
}

public class Main {
public static void main(String[] args) {
User user = new User("user123", "secret");

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(user);
System.out.println(json); // Output: {"username":"user123"}
}
}

Customizing Field Names with @SerializedName

For cases where you need to serialize a Java field to a specific JSON field name, Gson provides the @SerializedName annotation. This allows you to define exactly how each field should be named in the JSON output, offering flexibility without needing to implement a custom serializer.

import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
class Employee {
@SerializedName("emp_name")
private String name;
@SerializedName("emp_id")
private String id;
@SerializedName("department")
private String dept;
}

public class GsonExample {
public static void main(String[] args) {
Employee employee = new Employee("John Doe", "1234", "Engineering");

Gson gson = new Gson();
String json = gson.toJson(employee);
System.out.println(json); // Output: {"emp_name":"John Doe","emp_id":"1234","department":"Engineering"}
}
}

Conclusion

By combining the power of Lombok’s annotation-driven code reduction with Gson’s flexible serialization capabilities, Java developers can significantly streamline the process of working with JSON data. This approach not only makes code easier to write and maintain but also provides the flexibility needed to meet the specific requirements of JSON serialization without resorting to implementing custom serializers. Embrace the synergy between Lombok and Gson to elevate your Java development to new levels of efficiency and clarity.

--

--

Hatim Tachi

My name is Hatim and I am a passionate Data Tech Lead in the technology industry.