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 include 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.gson;

import com.google.gson.Gson;
import org.kodejava.gson.support.People;

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:43:01 AM"}

Here is the People class.

package org.kodejava.gson.support;

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.10.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

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