Java Gson custom field name using @SerializedName annotation

Tags: JSON gson Gson toJson SerializedName

In this Java Gson tutorial we learn how to configure Gson to customize the field name during serialization JSON. Via step by step tutorial we will show you how to use the @SerializedName annotation to override field names.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: '', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.


Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at

How to custom field name using @SerializedName annotation

For example we have the Contact class as below.


public class Contact {
    private String firstName;
    private String lastName;

    private String email;

    private int age;
    private String address;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getAddress() {
        return address;

    public void setAddress(String address) {
        this.address = address;

As you can see in the Contact class above we have the @SerializedName(“emailAddress”) to override the field name from email to emailAddress.

In the following Java example program we show you how to serialize an object of Contact class above to JSON string.


public class SerializedNameExample {
    public static void main(String... args) {
        Contact contact = new Contact();
        contact.setAddress("123 street");

        Gson gson = new Gson();
        String jsonString = gson.toJson(contact);

        System.out.println("Output JSON: ");
The output is:
Output JSON: 
{"firstName":"Simple","lastName":"Solution","emailAddress":"","age":30,"address":"123 street"}

Happy Coding 😊