Core Java

Custom Field Names with @SerializedName in Gson

Gson is a popular Java library for converting Java objects to their JSON representation and vice versa. One of the challenges developers often face is handling JSON field names that do not exactly match the corresponding Java object field names. Fortunately, Gson provides a solution to this problem using the @SerializedName annotation.

1. Understanding @SerializedName

The @SerializedName annotation is used to specify a field name in JSON that is different from the field name used in the Java class. This is particularly useful when the JSON field names do not follow Java naming conventions or when they are inconsistent.

2. Basic Usage of @SerializedName

Before using the @SerializedName annotation, we need to set up Gson in our project. Using Maven we can do this by declaring the Gson dependency in our pom.xml file:

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.11.0</version>
        </dependency>

Let us consider a simple example where we have a JSON object with field names that do not match the Java object field names.

JSON Example

{
  "user_name": "JohnDoe",
  "user_email": "john.doe@javacodegeeks.com",
  "user_age": 30
}

2.1 Java Class without @SerializedName

If we directly map this JSON to a Java class without using @SerializedName, Gson will not be able to correctly deserialize the JSON fields.

public class User {

    private String userName;
    private String userEmail;
    private int userAge;

    // Getters and setters
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
}

Attempting to deserialize the JSON into this class will result in null values for all fields because the JSON field names do not match the Java field names.

public class GsonSerializedNameExample {

    public static void main(String[] args) {
        String json = "{\"user_name\":\"JohnDoe\", \"user_email\":\"john.doe@javacodegeeks.com\", \"user_age\":30}";

        Gson gson = new Gson();
        User user = gson.fromJson(json, User.class);

        System.out.println("User Name: " + user.getUserName());
        System.out.println("User Email: " + user.getUserEmail());
        System.out.println("User Age: " + user.getUserAge());
    }
}

The program output will be:

Fig 1: Null Value Output without Custom Field Name (@SerializedName not used)
Fig 1: Null Value Output without Custom Field Name (@SerializedName not used)

2.2 Using @SerializedName to Match JSON Fields

To resolve this, we can use the @SerializedName annotation to specify the exact JSON field names.

import com.google.gson.annotations.SerializedName;

public class User {
    @SerializedName("user_name")
    private String userName;

    @SerializedName("user_email")
    private String userEmail;

    @SerializedName("user_age")
    private int userAge;

    // Getters and setters
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
}

With the @SerializedName annotation, Gson now knows how to map the JSON fields to the corresponding Java fields correctly.

2.4 Serialization Example

The @SerializedName annotation also works for serialization, ensuring that the Java field names are correctly converted to the specified JSON field names.

public class GsonSerializedNameExample {

    public static void main(String[] args) {

        User user = new User();
        user.setUserName("JaneDoe");
        user.setUserEmail("jane.doe@javacodegeeks.com");
        user.setUserAge(25);

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

        System.out.println(json);

    }
}

The output will be:

{"user_name":"JaneDoe","user_email":"jane.doe@javacodegeeks.com","user_age":25}

3. Conclusion

The @SerializedName annotation is a feature in Gson that allows developers to map JSON field names to Java field names that may not match. This ensures seamless serialization and deserialization, making the code more maintainable and easier to understand. By leveraging @SerializedName, we can work with inconsistent JSON formats without compromising our Java code quality.

4. Download the Source Code

This was an article on Custom Field Name with SerializedName in Gson.

Download
You can download the full source code of this example here: Gson custom field name with serializedname

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button