How does Gson handles object fields?

In this example you’ll see how the Gson library handles the object fields. For object fields to be serialized into JSON string it doesn’t need to use any annotations, it can even read private fields. If you have a null value field it will not be serialized into JSON string. To exclude a field from serialization you can mark the field with the transient keyword.

In the snippet below we create a People object. This object has a null value field named age, this will not included in the serialization because we didn’t assign any value to it. The secret field is also not serialized because we mark it with transient keyword.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

import java.util.Calendar;

public class GsonFieldExample {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(1980, Calendar.NOVEMBER, 11);
        People people = new People("John", "350 Banana St.", dob.getTime());
        people.setSecret("This is a secret!");

        Gson gson = new Gson();
        String json = gson.toJson(people);
        System.out.println("json = " + json);
    }
}

If your run the code above you’ll see the following line printed:

json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}

Here is the People class.

package org.kodejava.example.google.gson;

import java.util.Date;

public class People {
    private String name;
    private String address;
    private Date dateOfBirth;
    private Integer age;
    private transient String secret;

    public People(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply