如何在Java中使用Gson实施自定义FieldNamingStrategy?
该FieldNamingStrategy 是在GSON提供自定义字段命名的机制。这允许客户端代码将字段名称转换为常规Java字段声明规则不支持的特定约定。该translateName()方法将前缀字符串“每个字段名pre_”。
在下面的示例中,我们可以实现CustomFieldNamingStrategy。
示例
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(); } } } //员工阶层 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; } }
输出结果
{"pre_empId":115,"pre_firstName":"Adithya","pre_lastName":"Jai"}