- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement custom FieldNamingStrategy using Gson in Java?
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"}
Advertisements
To Continue Learning Please Login
Login with Google