Friday, 5 February 2021

@Expose annotation : GSON : How to exclude / include the fields in serialisation & deserialisation ?

You can use @Expose annotation to exclude or include the fields using GSON library.

By default, @Expose serialize & deserialize attributes have true. So you can mention @Expose directly, which intends @Expose(serialize = true, deserialize = true)
Maven Dependency Need: Add this dependency in your pom.xml file.
For Example:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

public class GsonExposeAnnotationTest {
public static void main(String[] args) {
Customer customer = new Customer("Dinesh", "CID124", new Integer(12));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(customer));

gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(customer));


}
}

class Customer {
@Expose(serialize = true, deserialize = true)
public String customerName;
@Expose(serialize = true, deserialize = true)
public String customerId;
@Expose(serialize = false, deserialize = false)
public Integer totalAssets;

public Customer(String customerName, String customerId, Integer totalAssets) {
this.customerName = customerName;
this.customerId = customerId;
this.totalAssets = totalAssets;
}
}

Input:
{
  "customerName": "Dinesh",
  "customerId": "CID124",
  "totalAssets": 12
}

output: Only exposed fields are in the seen in the output after serialisation.
{ "customerName": "Dinesh", "customerId": "CID124" }


No comments:

Post a Comment