如何在 Java 中使用 Gson 实现自定义 FieldNamingStrategy?
javajsonobject oriented programmingprogramming
FieldNamingStrategy 是一种在 Gson 中提供自定义字段命名的机制。这允许客户端代码将字段名称转换为常规 Java 字段声明规则不支持的特定约定。translateName() 方法将在每个字段名称前加上字符串"pre_"作为前缀。
在下面的示例中,我们可以实现自定义 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"}