**注解的作用:**转换 key 关键字,json 转换成对象是,json 字段的 key 默认必须和声明类的字段名称一样。但是如果服务器返回的数据中 key 是关键字,这该怎么办?例如 key 是 case、switch 等,我们在声明类的时候是不能用这些字段的。或许你会让服务端那边改动,那服务端可能要改动非常的大,但是实际情况是不太愿意去改的。而这时候重命名注解就派上用场了。
还有就是如果服务端返回的 json 的 key 太冗余、或是不直观,这是就可以简化一下,代码看起来比较的优雅。
#####替换关键字的 key:
public class AnnotationTest { public class Person { private int per_id; private String name; private String sex; @SerializedName(“case”) private int case_num; public Person(int per_id, String name, String sex, int case_num) { super(); this.per_id = per_id; this.name = name; this.sex = sex; this.case_num = case_num; } @Override public String toString() { return “Person–>[per_id=” + per_id + “, name=” + name + “, sex=” + sex + “, case_num=” + case_num + “]”; } } public static void main(String[] args) { Gson gson = new Gson(); String json_str = “{“per_id”:1,“name”:“layne”,“sex”:“man”,“case”:18}”; Person person = gson.fromJson(json_str, Person.class); System.out.println(“服务端发送的情况:”+json_str); System.out.println(“移动端转换的情况:”+person); } }
#####运行结果:
替换冗余、难看的 key:
public class AnnotationTest1 { public class Person { private int per_id; private String name; private String sex; @SerializedName(“home_light_state”) private boolean state; public Person(int per_id, String name, String sex, boolean state) { super(); this.per_id = per_id; this.name = name; this.sex = sex; this.state = state; } @Override public String toString() { return “Person [per_id=” + per_id + “, name=” + name + “, sex=” + sex + “, state=” + state + “]”; } } public static void main(String[] args) { Gson gson = new Gson(); String json_str = “{“per_id”:1,“name”:“layne”,“sex”:“man”,“home_light_state”:true}”; Person person = gson.fromJson(json_str, Person.class); System.out.println(“服务端发送的情况:”+json_str); System.out.println(“移动端转换的情况:”+person); } }
#####运行结果:
**注解作用2:**结合 alternate 提供多种备用字段key来解析,@SerializedName(value = “state”, alternate = { “plus”, “all” })
如果 json 中有 plus 就会解析成 state,如果有 all 也会解析成 state,当然
state 依旧不变的。
**注意1:**value 中的值不能出现在 alternate 中;
**注意2:**alternate 的备选字段会后面的替换前面的。
#####实例代码:
public class AnnotationTest2 { public class Person { private int per_id; private String name; private String sex; @SerializedName(value = “state”, alternate = { “plus”, “all” }) private String state; public Person(int per_id, String name, String sex, String state) { super(); this.per_id = per_id; this.name = name; this.sex = sex; this.state = state; } @Override public String toString() { return “Person [per_id=” + per_id + “, name=” + name + “, sex=” + sex + “, state=” + state + “]”; } } public static void main(String[] args) { Gson gson = new Gson(); String json_str = “{“per_id”:1,“name”:“layne”,“sex”:“man”,“all”:“广东