Exclude fields from Serialization with GSON API

GSON is a Java serialization/deserialization library to convert Java Objects into JSON and back.

In this post, we are going to see how we can exclude some fields from serialization with the GSON API.

Refer the below model class.

Employee.java



import org.apache.commons.lang3.builder.ToStringBuilder;

public class Employee {

    private String firstName;
    private String lastName;
    private int salary;

    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 int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

The above Employee class has three fields such as first name, last name and salary. Consider that we want to exclude the salary field while serializing the employee object.

To do so, then we have to create a class which implements the ExclusionStrategy interface and provide our logic over there.

SalaryExclusionStrategy.java


import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class SalaryExclusionStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return "salary".equalsIgnoreCase(f.getName());
    }

    @Override
    public boolean shouldSkipClass(Class clazz) {
        return false;
    }
}


We need to instruct the GSON parser to ignore the salary field. So while creating the GSON object, we have to pass an instance of SalaryExclusionStrategy which contains the logic to ignore the salary field to the addSerializationExclusionStrategy method.

Refer the below code to know how we can do that.


import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonMain {

    private static final Gson GSON = new GsonBuilder()
            .setFieldNamingStrategy(FieldNamingPolicy.IDENTITY)
            .setPrettyPrinting()
            .addSerializationExclusionStrategy(new SalaryExclusionStrategy())
            .create();

    public static void main(String[] args) {
        Employee employee = new Employee();
        employee.setFirstName("Bala");
        employee.setLastName("Samy");
        System.out.println(GSON.toJson(employee));
    }
}


Refer below the output.


{
  "firstName": "Bala",
  "lastName": "Samy"
}

Advertisements

GSON library ignores new/missing fields

I have recently came across GSON library and found out that it ignores new/missing fields in the JSON response while doing unmarshalling by default. We won’t need to specify any annotations or properties to do so.

Please refer the below example

pom.xml


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

User.java


import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = -8486882160753981372L;

    private String fname;

    private String lastname;

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("fname", fname)
                .append("lastname", lastname)
                .toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        return new EqualsBuilder()
                .append(fname, user.fname)
                .append(lastname, user.lastname)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(fname)
                .append(lastname)
                .toHashCode();
    }
}

GsonMain.java


import com.google.gson.Gson;

public class GsonMain {

    private static Gson gson = new Gson();

    public static void main(String[] args) {
        String response = "{\"fname\": \"bala,\", \"mname\": \"k,\", \"lastname\": \"samy\"}";
        User user = (User) fromJson(response, User.class);
        System.out.println("Converting JSON to object. user:" + user);
        System.out.println("Converting Object to JSON. user:" + toJson(user));
    }

    public static Object fromJson(String response, Class className) {
        return gson.fromJson(response, className);

    }

    public static String toJson(User user) {
        return gson.toJson(user);

    }
}

In GsonMain.main(), I try to parse the response to User object and vice versa. In User class, I have only fname and lastname but in the response string has a new field and its value[mname]. So while parsing the response, we wont see any error since the GSON lib ignores that field and parse only the known fields.