Gson – exclude or ignore specific fields example shows how to exclude fields or ignore fields while serialization or deserialization using the Gson library in Java.
How to exclude or ignore fields from serialization in Java Gson?
There are several ways using which we can exclude fields while serializing to the JSON.
1. Using the transient
The easiest way to exclude specific fields from serialization is to mark them as transient fields. In the below given example, I’ve marked the age field as transient, so it will not be included in the JSON when the object is serialized.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonExcludeFieldsExample { public static void main(String[] args) { Employee employee = new Employee("EMP001", "Bob", 23); Gson gson = new GsonBuilder() .setPrettyPrinting() .create(); String json = gson.toJson(employee); System.out.println(json); } } class Employee{ private String id; private String name; private transient int age; public Employee(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
Output
1 2 3 4 |
{ "id": "EMP001", "name": "Bob" } |
As we can see from the output, the age field is ignored and excluded from the JSON.
Important Note: While this approach is the easiest, it ignores the field marked as transient from being serialized and deserialized. If you want to ignore a specific field only during serialization or deserialization, this approach will not work.
2. Using the Expose annotation
We can also mark all the fields with the Expose annotation that we want to serialize or deserialize. We also need to create a Gson object using the GsonBuilder along with the excludeFieldsWithoutExposeAnnotation
method call as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; public class GsonExcludeFieldsExample { public static void main(String[] args) { Employee employee = new Employee("EMP001", "Bob", 23); Gson gson = new GsonBuilder() .setPrettyPrinting() .excludeFieldsWithoutExposeAnnotation() .create(); String json = gson.toJson(employee); System.out.println(json); } } class Employee{ @Expose private String id; @Expose private String name; private int age; public Employee(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
Output
1 2 3 4 |
{ "id": "EMP001", "name": "Bob" } |
In this approach, we need to mark all the fields with the Expose annotation that we want to serialize/deserialize. If we have hundreds of fields, it might be cumbersome to mark all of them with the annotation.
3. Using the exclusion strategy
We can set the exclusion strategy while creating the Gson object using the GsonBuilder by using the setExclusionStrategies
method. We need to implement the ExclusionStrategy interface in our custom strategy class and pass an object of it to the setExclusionStrategies
method as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
package com.javacodeexamples.gsonexamples; import java.util.Arrays; import java.util.List; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonExcludeFieldsExample { public static void main(String[] args) { Employee employee = new Employee("EMP001", "Bob", Arrays.asList( new Company("Wipro", 2, "Pune"), new Company("Infosys", 5, "Delhi")) ); /* * Create Gson object with the custom strategy * to exclude field "name" from serialization */ Gson gson = new GsonBuilder() .setPrettyPrinting() .setExclusionStrategies(new EmployeeExclusionStretegy()) .create(); String json = gson.toJson(employee); System.out.println(json); } } /* * Custom exclusion strategy */ class EmployeeExclusionStretegy implements ExclusionStrategy{ public boolean shouldSkipClass(Class<?> arg0) { return false; } /* * Return false for all the fields you want to ignore/exclude */ public boolean shouldSkipField(FieldAttributes attr) { /* * We want to exclude the "name" field */ return attr.getName().equals("name"); } } class Employee{ private String id; private String name; private List<Company> companies; public Employee(String id, String name, List<Company> companies) { this.id = id; this.name = name; this.companies = companies; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Company> getCompanies() { return companies; } public void setCompanies(List<Company> companies) { this.companies = companies; } } class Company{ private String name; private int numberOfYears; private String location; public Company(String name, int numberOfYears, String location) { this.name = name; this.numberOfYears = numberOfYears; this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumberOfYears() { return numberOfYears; } public void setNumberOfYears(int numberOfYears) { this.numberOfYears = numberOfYears; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ "id": "EMP001", "companies": [ { "numberOfYears": 2, "location": "Pune" }, { "numberOfYears": 5, "location": "Delhi" } ] } |
As we can see from the output, the “name” field is ignored/excluded from the generated JSON from both the classes, Employee, and Company.
If we want to ignore just the company name, we can make the below-given changes to the strategy.
1 2 3 4 5 6 7 8 |
public boolean shouldSkipField(FieldAttributes attr) { /* * We want to exclude the "name" field, but only from * the Company class, not from Employee class */ return attr.getName().equals("name") && attr.getDeclaringClass() == Company.class; } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "id": "EMP001", "name": "Bob", "companies": [ { "numberOfYears": 2, "location": "Pune" }, { "numberOfYears": 5, "location": "Delhi" } ] } |
Now, only the “name” field of the Company class is ignored.
The ExclusionStretegies apply to both, serialization and deserialization. If we want to apply the strategy to either one of them or if we want to apply a different strategy for serialization and deserialization, we can use the addSerializationExclusionStrategy
and addDeserializationExclusionStrategy
methods instead of the setExclusionStrategies
method while creating a Gson object.
Please let me know your views in the comments section below.