How to implement custom FieldNamingStrategy using Gson in Java?

JavaJSONObject Oriented ProgrammingProgramming

The FieldNamingStrategy is a mechanism for providing custom field naming in Gson. This allows the client code to translate field names into a particular convention that is not supported as a normal Java field declaration rules. The translateName() method will prefix every field name with the string “pre_”.

In the below example, we can implement the Custom FieldNamingStrategy.

Example

import java.lang.reflect.Field;
import com.google.gson.*;
public class GsonFieldNamingStrategyTest {
   public static void main(String[] args) {
      Employee emp = new Employee();
      emp.setEmpId(115);
      emp.setFirstName("Adithya");
      emp.setLastName("Jai");
      CustomFieldNamingStrategy customFieldNamingStrategy = new CustomFieldNamingStrategy();
      GsonBuilder gsonBuilder = new GsonBuilder();
      Gson gson = gsonBuilder.setFieldNamingStrategy(customFieldNamingStrategy).create();
      String result = gson.toJson(emp);
      System.out.println(result);
   }
   // Custom FieldNamingStrategy
   private static class CustomFieldNamingStrategy implements FieldNamingStrategy {
      @Override
      public String translateName(Field field) {
         return "pre_" + field.getName();
      }
   }
}
// Employee class
class Employee {
   private int empId;
   private String firstName;
   private String lastName;
   public int getEmpId() {
      return empId;
   }
   public void setEmpId(int empId) {
      this.empId = empId;
   }
   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;
   }
}

Output

{"pre_empId":115,"pre_firstName":"Adithya","pre_lastName":"Jai"}
raja
Published on 24-Oct-2019 12:58:57
Advertisements