There are a lot of great Java libraries for working with JSON. One of these is Google’s Gson, which has the goal of providing simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.

Often when serializing objects into JSON you will want to exclude certain object fields. There a couple of ways to do this. First, you can mark certain fields as transient. Fields marked as transient are not meant to be part of the persistent state of the object, and are therefore not serialized. The other way is to create a custom ExclusionStrategy which will specify which fields or classes should be serialized or deserialized as part of the JSON output/input.

Below is a simple example of creating a BdPerson object (class definition below), populating the fields with values, and outputting to JSON. The Gson object is created with a custom ExclusionStrategy which will prevent certain fields such as “header” from being part of the JSON output.

Documentation on ExclusionStrategy can be found here. This example can be found in the Big Datums GitHub repo.

Create JSON String:

public static void main(String[] args){
    Gson gson = new GsonBuilder().setExclusionStrategies(new BdDataGenCustomExclusionStrategy()).create();
    BdPerson p = new BdPerson();
    p.populateRandom(Fairy.create(), false);
    String s = gson.toJson(p);
    System.out.println(s);
}

Output:

{
	"id": 1,
	"username": "kimberlym",
	"email_address": "[email protected]",
	"phone_number": "909-687-689",
	"first_name": "Kimberly",
	"last_name": "Meyer",
	"middle_name": "",
	"sex": "FEMALE",
	"birthdate": "2006-10-04",
	"join_date": "2007-06-04T15:26:36.688-07:00",
	"previous_logins": 2995,
	"last_ip": "49.5.103.29"
}

BdPerson Class:

package com.bigdatums.datagen;

import org.jfairy.Fairy;
import org.jfairy.producer.BaseProducer;
import org.jfairy.producer.DateProducer;
import org.jfairy.producer.net.NetworkProducer;
import org.jfairy.producer.person.Person;
import java.util.Random;

public class BdPerson {
    public String[] header = {"id","username","email_address","phone_number","first_name","last_name","middle_name","sex","birthdate","join_date","previous_logins","last_ip"};

    public int id;
    public String username;
    public String email_address;
    public String phone_number;
    public String first_name;
    public String last_name;
    public String middle_name;
    public String sex;
    public String birthdate;
    public String join_date;
    public int previous_logins;
    public String last_ip;

    private int currId = 0;
    private Random r = new Random();

    public void populateRandom(Fairy fairy, boolean randId) {
        Person person = fairy.person();
        DateProducer dp = fairy.dateProducer();
        BaseProducer bp = fairy.baseProducer();
        NetworkProducer np = fairy.networkProducer();

        if(randId) currId = r.nextInt(20000000);
        else currId++;

        id = currId;
        username = person.username();
        email_address = person.email();
        phone_number = person.telephoneNumber();
        first_name = person.firstName();
        last_name = person.lastName();
        middle_name = person.middleName();
        sex = person.sex().name();
        birthdate = person.dateOfBirth().toLocalDate().toString();
        join_date = dp.randomDateBetweenYearAndNow(2005).toString();
        previous_logins = bp.randomBetween(1,10000);
        last_ip = np.ipAddress();
    }

    public String[] toArray(){
        String[] personArr = {Integer.toString(id),username,email_address,phone_number,first_name,last_name,middle_name,sex,birthdate,join_date,Integer.toString(previous_logins),last_ip};
        return personArr;
    }

    public String headerToString() {
        return headerToString("\t");
    }

    public String headerToString(String sep) {
        return String.join(sep, header);
    }

    public String toString() {
        return toString("\t");
    }

    public String toString(String sep) {
        return String.join(sep, toArray());
    }

}

Custom ExclusionStrategy:

package com.bigdatums.datagen;

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

public class BdDataGenCustomExclusionStrategy implements ExclusionStrategy {

    public boolean shouldSkipField(FieldAttributes f) {
        if(f.getDeclaringClass() == BdPerson.class && (f.getName().equals("header") || f.getName().equals("r") || f.getName().equals("currId")))
            return true;
        else return false;
    }

    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }

}

Leave a Reply

How to Exclude Fields using Gson