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