RelationDigest

Wednesday, 1 November 2023

[New post] Exclude Fields from Serialization in Gson – @Expose Annotation

Site logo image vibssingh posted: " HOME The previous tutorials have explained the conversion of Java Object to JSON using Gson API. This tutorial explains the process of excluding the attributes from the JSON using Gson API. @Expose helps control what class attributes can be" QA Automation Expert

Exclude Fields from Serialization in Gson – @Expose Annotation

vibssingh

Nov 1

HOME

The previous tutorials have explained the conversion of Java Object to JSON using Gson API. This tutorial explains the process of excluding the attributes from the JSON using Gson API.

@Expose helps control what class attributes can be serialized or deserialized.

@Expose is optional and offers two configuration parameters :

  • serialize – If true, the field marked with this annotation is written out in the JSON while serializing.
  • deserialize – If true, the field marked with this annotation is deserialized from the JSON.
 @Expose(serialize = false) private String lastName;  @Expose (serialize = false, deserialize = false) private String emailAddress 

Add the below dependency to POM.xml to use Gson API.

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

Let us take an example of a JSON.

 {   "firstName": "Vibha",   "lastName": "Singh",   "salary": {     "2018": 14000,     "2012": 12000,     "2010": 10000   },   "designation": "Manager",   "emailId": [     "abc@test.com",     "vibha@test.com"   ] } 

Let us create a table named Employee which contains the data members same as node names in the above JSON payload with @Expose annotation and their corresponding getter and setter methods.

 package com.example.gson;  import com.google.gson.annotations.Expose;  import java.math.BigDecimal; import java.util.List; import java.util.Map;  public class Employee {      // private data members of POJO class      @Expose(serialize = true)     private String firstName;      @Expose(serialize = true)     private String lastName;      @Expose(serialize = false)     private int age;      @Expose(serialize = true)     private Map<String, BigDecimal> salary;      @Expose()     private String designation;      @Expose(serialize = false)     private String contactNumber;      @Expose(serialize = true)     private List<String> emailId;      // Getter and setter methods     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 getAge() {         return age;     }      public void setAge(int age) {         this.age = age;     }      public Map<String, BigDecimal> getSalary() {         return salary;     }      public void setSalary(Map<String, BigDecimal> salary) {         this.salary = salary;     }      public String getDesignation() {         return designation;     }      public void setDesignation(String designation) {         this.designation = designation;     }      public String getContactNumber() {         return contactNumber;     }      public void setContactNumber(String contactNumber) {         this.contactNumber = contactNumber;     }      public List<String> getEmailId() {         return emailId;     }      public void setEmailId(List<String> emailId) {         this.emailId = emailId;     }      @Override     public String toString() {         return "(firstName: " + firstName + "," +                 "lastName: " + lastName + "," +                 "age: " + age + ", " +                 "salary: " + salary + "," +                 "designation: " + designation + ", " +                 "contactNumber: " + contactNumber + ", " +                 "emailId: " + emailId + ")";      } } 

Suppose the attribute age and contactNumber in the Employee class should not serialize because it's sensitive information. Hence, we must decorate these attributes with the annotation @Expose(serialize=false):

To use @Expose annotation, we must create a Gson instance by using the GsonBuilder class and its excludeFieldsWithoutExposeAnnotation() method.

 import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.junit.Test; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map;  public class GsonExpose_Demo {      @Test     public void gsonExposeTest()  {          // Create an object of POJO class         Employee employee = new Employee();         employee.setFirstName("Vibha");         employee.setLastName("Singh");         employee.setAge(30);         Map<String, BigDecimal> salary = new HashMap() {{             put("2010", new BigDecimal(10000));             put("2012", new BigDecimal(12000));             put("2018", new BigDecimal(14000));         }};          employee.setSalary(salary);         employee.setDesignation("Manager");         employee.setContactNumber("+919999988822");         employee.setEmailId(Arrays.asList("abc@test.com","vibha@test.com"));          Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();         String employeeJsonPayload = gson.toJson(employee);         System.out.println("Json :" + employeeJsonPayload);      } } 

The output of the above program is shown below.

We can see here that age and contactNumber are not shown in the JSON body.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Comment
Like
Tip icon image You can also reply to this email to leave a comment.

Manage your email settings or unsubscribe.

Trouble clicking? Copy and paste this URL into your browser:
http://qaautomation.expert/2023/11/01/exclude-fields-from-serialization-in-gson-expose-annotation/

WordPress.com and Jetpack Logos

Get the Jetpack app to use Reader anywhere, anytime

Follow your favorite sites, save posts to read later, and get real-time notifications for likes and comments.

Download Jetpack on Google Play Download Jetpack from the App Store
WordPress.com on Twitter WordPress.com on Facebook WordPress.com on Instagram WordPress.com on YouTube
WordPress.com Logo and Wordmark title=

Automattic, Inc. - 60 29th St. #343, San Francisco, CA 94110  

at November 01, 2023
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

No comments:

Post a Comment

Newer Post Older Post Home
Subscribe to: Post Comments (Atom)

Episode 7 - Intel, Israel, Islamism

Listen now (92 mins) | A grab bag of garbage. ͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏  ...

  • [New post] Wiggle Kingdom: April Earnings on Spring Savings!
    Betsi...
  • [New post] Balancing the ‘E’ and ‘S’ in Environment, Social and Governance (ESG) crucial to sustaining liquidity and resilience in the African loan market (By Miranda Abraham)
    APO p...
  • Something plus something else
    Read on bl...

Search This Blog

  • Home

About Me

RelationDigest
View my complete profile

Report Abuse

Blog Archive

  • August 2025 (48)
  • July 2025 (59)
  • June 2025 (53)
  • May 2025 (47)
  • April 2025 (42)
  • March 2025 (30)
  • February 2025 (27)
  • January 2025 (30)
  • December 2024 (37)
  • November 2024 (31)
  • October 2024 (28)
  • September 2024 (28)
  • August 2024 (2729)
  • July 2024 (3249)
  • June 2024 (3152)
  • May 2024 (3259)
  • April 2024 (3151)
  • March 2024 (3258)
  • February 2024 (3046)
  • January 2024 (3258)
  • December 2023 (3270)
  • November 2023 (3183)
  • October 2023 (3243)
  • September 2023 (3151)
  • August 2023 (3241)
  • July 2023 (3237)
  • June 2023 (3135)
  • May 2023 (3212)
  • April 2023 (3093)
  • March 2023 (3187)
  • February 2023 (2865)
  • January 2023 (3209)
  • December 2022 (3229)
  • November 2022 (3079)
  • October 2022 (3086)
  • September 2022 (2791)
  • August 2022 (2964)
  • July 2022 (3157)
  • June 2022 (2925)
  • May 2022 (2893)
  • April 2022 (3049)
  • March 2022 (2919)
  • February 2022 (2104)
  • January 2022 (2284)
  • December 2021 (2481)
  • November 2021 (3146)
  • October 2021 (1048)
Powered by Blogger.