@SerializedName注解详解
@SerializedName
是 Google Gson 库中的一个关键注解,用于解决 Java 对象字段名与 JSON 属性名不一致的问题。它在 JSON 序列化(对象转 JSON)和反序列化(JSON 转对象)过程中起到桥梁作用。
一、核心功能
1. 字段名映射
public class User {@SerializedName("user_name")private String username;@SerializedName("email_address")private String email;
}
序列化:Java 字段
username
→ JSON 属性"user_name"
反序列化:JSON 属性
"user_name"
→ Java 字段username
2. 解决命名差异
驼峰命名(Java) ↔ 蛇形命名(JSON API)
缩写差异:
id
vsuser_id
语言差异:
nombre
(西语) vsname
二、使用方法
1. 基本用法
public class Product {@SerializedName("product_id")private Long id;@SerializedName("product_name")private String name;
}
2. 多名称映射(Gson 2.4+)
public class Order {@SerializedName(value = "order_date", alternate = {"date", "created_at"})private Date orderDate;
}
序列化:始终使用
value
值("order_date"
)反序列化:可接受三种名称:
"order_date"
"date"
"created_at"
三、实际应用场景
1. 对接第三方 API
// GitHub API 返回的 JSON
{"login": "octocat","avatar_url": "https://github.com/images/error/octocat_happy.gif"
}// Java 映射类
public class GitHubUser {@SerializedName("login")private String username;@SerializedName("avatar_url")private String avatarUrl;
}
2. 数据库字段映射
// 数据库字段:first_name, last_name
public class Person {@SerializedName("first_name")private String firstName;@SerializedName("last_name")private String lastName;
}
3. 版本兼容
public class Configuration {@SerializedName(value = "timeout", alternate = {"request_timeout", "api_timeout"})private int timeout;
}
兼容新旧版本 API 的不同字段名
四、与其它方案对比
方案 | 优点 | 缺点 |
---|---|---|
@SerializedName | 声明式配置 | 需添加Gson依赖 |
GsonBuilder | 全局命名策略 | 不够灵活 |
手动映射 | 完全控制 | 代码冗余 |
Jackson @JsonProperty | 功能类似 | 需Jackson库 |
五、完整工作流程
六、最佳实践
1. 统一命名策略
// 使用GsonBuilder配置全局策略
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
2. 结合使用
public class Product {@SerializedName("prod_id")private Long id; // 特殊字段单独映射// 其他字段使用全局策略private String productName; // 自动映射为 product_name
}
3. 枚举处理
public enum Status {@SerializedName("active")ACTIVE,@SerializedName("inactive")INACTIVE,@SerializedName("pending")PENDING
}
七、常见问题解决方案
1. 字段名变化兼容
public class User {@SerializedName(value = "email", alternate = {"email_address", "user_email"})private String email;
}
2. 嵌套对象映射
public class Order {@SerializedName("order_id")private Long id;@SerializedName("customer_info")private Customer customer;
}public class Customer {@SerializedName("cust_name")private String name;
}
3. 默认值处理
public class Settings {@SerializedName("notification_enabled")private boolean notificationEnabled = true; // 默认值
}
八、进阶用法
1. 自定义序列化/反序列化
public class CustomDateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");@Overridepublic JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {return new JsonPrimitive(format.format(src));}@Overridepublic Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {try {return format.parse(json.getAsString());} catch (ParseException e) {throw new JsonParseException(e);}}
}// 使用自定义适配器
public class Event {@SerializedName("event_date")@JsonAdapter(CustomDateAdapter.class)private Date date;
}
2. 排除字段
public class SensitiveData {@SerializedName("user_id")private Long userId;@Expose(serialize = false) // 不序列化private String password;
}
九、与其他库集成
1. Retrofit 网络请求
public interface GitHubService {@GET("users/{username}")Call<GitHubUser> getUser(@Path("username") String username);
}// 自动使用@SerializedName映射
GitHubUser user = new Gson().fromJson(response.body(), GitHubUser.class);
2. Spring Boot 配置
@Configuration
public class GsonConfig {@Beanpublic Gson gson() {return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();}
}
十、总结
1. 核心价值
解耦:分离Java字段名与JSON属性名
兼容:处理不同命名规范的系统对接
灵活:支持多名称映射和版本兼容
2. 使用场景
REST API 开发
第三方服务集成
数据库实体映射
配置文件解析
微服务间通信
3. 最佳实践
优先使用全局策略:统一命名规范
局部覆盖:特殊字段使用
@SerializedName
版本兼容:使用
alternate
处理字段变更安全考虑:敏感字段使用
@Expose
控制序列化
@SerializedName
是处理 Java 对象与 JSON 数据映射的关键工具,特别在与外部系统对接时,能显著提高代码的可读性和可维护性。