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



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


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;

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

    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)

    public int hashCode() {
        return new HashCodeBuilder(17, 37)


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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s