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.