Exclude fields from Serialization with GSON API

GSON is a Java serialization/deserialization library to convert Java Objects into JSON and back.

In this post, we are going to see how we can exclude some fields from serialization with the GSON API.

Refer the below model class.

Employee.java



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

public class Employee {

    private String firstName;
    private String lastName;
    private int salary;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

The above Employee class has three fields such as first name, last name and salary. Consider that we want to exclude the salary field while serializing the employee object.

To do so, then we have to create a class which implements the ExclusionStrategy interface and provide our logic over there.

SalaryExclusionStrategy.java


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

public class SalaryExclusionStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return "salary".equalsIgnoreCase(f.getName());
    }

    @Override
    public boolean shouldSkipClass(Class clazz) {
        return false;
    }
}


We need to instruct the GSON parser to ignore the salary field. So while creating the GSON object, we have to pass an instance of SalaryExclusionStrategy which contains the logic to ignore the salary field to the addSerializationExclusionStrategy method.

Refer the below code to know how we can do that.


import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonMain {

    private static final Gson GSON = new GsonBuilder()
            .setFieldNamingStrategy(FieldNamingPolicy.IDENTITY)
            .setPrettyPrinting()
            .addSerializationExclusionStrategy(new SalaryExclusionStrategy())
            .create();

    public static void main(String[] args) {
        Employee employee = new Employee();
        employee.setFirstName("Bala");
        employee.setLastName("Samy");
        System.out.println(GSON.toJson(employee));
    }
}


Refer below the output.


{
  "firstName": "Bala",
  "lastName": "Samy"
}

Advertisements

Convert Object to JSON and JSON to Object with FasterXML/jackson-databind

Refer the FasterXml/Jackson-bind API from the below GitHub repo. This is very helpful for handling the various data format especially JSON

https://github.com/FasterXML/jackson-databind

The sample code to convert Object to JSON and JSON to Object is given below,

Maven Dependencies,


 <dependency>
            <groupId>com.fasterxml.jackson.jr</groupId>
            <artifactId>jackson-jr-objects</artifactId>
            <version>2.5.0</version>
 </dependency>
 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
    </dependency>

Code:


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws JsonProcessingException {
        String content = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            content = mapper.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return content;
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {

        Customer customer = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            customer = mapper.readValue(content, Customer.class);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return customer;
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


Converting Object to String
Converting String:{"firstName":"Bala","lastName":"samy","customerId":"cust1234"}
Converting String to Customer Object
Converted Object:JSONUtils$Customer@130f889[firstName=Bala,lastName=samy,customerId=cust1234]

Convert Object as Json using FasterXML/jackson-jr

Its an alternative to jackson-bind API for processing JSON. It provides an easy way to convert the java object to json and vice versa.

This API can be used, when the size of the third party jar and startup time matters in your application. This API has very low initialization overhead compared to jackson-bind

The Github repository is https://github.com/FasterXML/jackson-jr

pom.xml


<dependency>
  <groupId>com.fasterxml.jackson.jr</groupId>
  <artifactId>jackson-jr-objects</artifactId>
  <version>2.8.5</version>
</dependency>

Sample code to convert the Object to json is given below,
JSONUtils:


import com.fasterxml.jackson.jr.ob.JSON;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws IOException {
        return JSON.std.asString(obj);
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {
        return JSON.std.beanFrom(Customer.class, content);
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


2016-12-29T11:44:54.319-0500 [main] INFO  o.c.o.m.JSONUtils - Converting Object to String
2016-12-29T11:44:54.398-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String:{"customerId":"cust1234","firstName":"Bala","lastName":"samy"}
2016-12-29T11:44:54.399-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String to Customer Object
2016-12-29T11:44:54.405-0500 [main] INFO  o.c.o.m.JSONUtils - Converted Object:org.cas.osd.mp.JSONUtils$Customer@31ef45e3[firstName=Bala,lastName=samy,customerId=cust1234]