注解 @SerializedName
/* * Note that MyClass.b is now deserialized from either name1, name2 or name3. * * @see com.google.gson.FieldNamingPolicy * * @author Inderjeet Singh * @author Joel Leitch */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface SerializedName { /** * @return the desired name of the field when it is serialized or deserialized */ String value(); /** * @return the alternative names of the field when it is deserialized */ String[] alternate() default {}; }来看一个例子:
public class UserSimple { @SerializedName("name") String name; String email; boolean isDeveloper; int age; }但是,假设有一刻 API 发生改变导致返回的 JSON 数据格式发生更改,接口返回了 "fullName" 而不是"name"。
{ "age": 26, "email": "norman@futurestud.io", "fullName": "Norman", "isDeveloper": true }不用担心,我们不要改动任何代码,我们只需要给类中改变的字段添加注解即可。
public class UserSimple { @SerializedName(value = "fullName", alternate="name") String name; String email; boolean isDeveloper; int age; }然而,假设有一刻 API 发生改变导致返回的 JSON 数据格式发生更改,接口返回了 "nickName" 而不是"name"和"fullName"
{ "age": 26, "email": "norman@futurestud.io", "fullName": "Norman", "isDeveloper": true } { "age": 26, "email": "norman@futurestud.io", "name": "Norman", "isDeveloper": true } { "age": 26, "email": "norman@futurestud.io", "nickName": "Norman", "isDeveloper": true }我们只需要给类中改变的字段添加注解即可。
public class UserSimple { @SerializedName(value = "fullName", alternate={"name","nickName"}) String name; String email; boolean isDeveloper; int age; }使用 Gson 进行注解,并在此运行,这就是是使用注解自动匹配的好处。
当然,你可以使用注解 @SerializedName 方式来保证命名规范,同时又可以正常映射接口字段,如果你的接口字段和命名规则差别很大,使用@SerializedName 注解来解决还是有必要的。
