GSON Excluding fields with modifiers from JSON
By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as “static” then by default it will be excluded. Here is another way you can exclude fields from GSON using modifiers.
Maven dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.memorynotfound.json.gson</groupId>
<artifactId>exclude-modifiers</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<gson.version>2.3.1</gson.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
</project>
Object to be Serialised/Deserialised
Note: that the id field has a protected modifier.
package com.memorynotfound.json;
import java.util.Date;
public class Product {
protected long id;
private String name;
private Date created;
private double amount;
public Product(long id, String name, Date created, double amount) {
this.id = id;
this.name = name;
this.created = created;
this.amount = amount;
}
}
GSON Excluding fields with modifiers from JSON
You must inform GSON to exclude certain fields. You can exclude fields by modifier using new GsonBuilder().excludeFieldsWithModifiers()
and insert the modifiers that you want to exclude.
Modifier.PROTECTED, Modifier.VOLATILE
.package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Modifier;
import java.util.Date;
public class ExcludeModifiersGson {
public static void main(String... args){
Product product = new Product(1, "Playstation 4", new Date(), 499.99);
Gson gson = new GsonBuilder().create();
String result = gson.toJson(product);
System.out.println(result);
gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.PROTECTED).create();
result = gson.toJson(product);
System.out.println(result);
}
}
Output
{"id":1,"name":"Playstation 4","created":"Dec 26, 2014 4:43:45 PM","amount":499.99}
{"name":"Playstation 4","created":"Dec 26, 2014 4:43:45 PM","amount":499.99}