Excluding field from JSON with @Expose GSON
GSON provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this @Expose GSON annotation, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
. The Gson instance created will exclude all fields in a class that are not marked with @Expose
annotation.
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-expose</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
The fields that are marked with the @Expose
annotation will be included in the JSON representation. So the fields that are not annotated e.g.: “created” will not be serialised into the JSON object.
package com.memorynotfound.json;
import com.google.gson.annotations.Expose;
import java.util.Date;
public class Product {
@Expose
private long id;
@Expose
private String name;
private Date created;
@Expose
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;
}
}
Excluding field from JSON using @Expose GSON
When creating your JSON object you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
. Otherwise the JSON object will not listen to the @Expose
annotation.
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;
public class ExcludeExposeGson {
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().excludeFieldsWithoutExposeAnnotation().create();
result = gson.toJson(product);
System.out.println(result);
}
}
Output
{"id":1,"name":"Playstation 4","created":"Dec 26, 2014 4:23:59 PM","amount":499.99}
{"id":1,"name":"Playstation 4","amount":499.99}
Good to know. However, is there a strategy that works on-the-fly? e.g. expose certain fields in certain use cases but not in others
You can dynamically exclude json fields from your pojo using a custom serializer.