首先声明,我是一个菜鸟。一下文章中出现技术误导情况盖不负责
gson的@Expose注解和@SerializedName注解
@Expose标签的2个属性.
1.1
(boolean) 反序列化 默认 true
1.2
(boolean) 序列化 默认 true
应用
new
GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
创立Gson对象,没有@Expose注释的属性将不会被序列化
public
class
User {
@Expose
private String username;
@Expose(serialize=false)
private int age ;
private List<String> list;
public User(String username, int age) {
super();
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public static void main(String []args){
User user = new User("lemon",27);
List<String> list = new ArrayList<String>();
list.add("l1");
list.add("l2");
user.setList(list);
Gson g1 = new Gson();
//应用 new Gson();
System.out.println(g1.toJson(user)); //{"username":"lemon","age":27,"list":["l1","l2"]}
//应用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson g2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(g2.toJson(user)); //{"username":"lemon"}
}
}
2.应用@
SerializedName标签定义属性序列化
后的名字
@Expose
@SerializedName("name")
private String username;
public static void main(String []args){
User user = new User("lemon",27);
List<String> list = new ArrayList<String>();
list.add("l1");
list.add("l2");
user.setList(list);
Gson g1 = new Gson();
//应用 new Gson();
//{"name":"lemon","age":27,"list":["l1","l2"]}
System.out.println(g1.toJson(user));
//应用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson g2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
//{"name":"lemon"}
System.out.println(g2.toJson(user));
}
文章结束给大家分享下程序员的一些笑话语录: N多年前,JohnHein博士的一项研究表明:Mac用户平均IQ要比PC用户低15%。超过6000多的参加者接受了测试,结果清晰的显示IQ比较低的人会倾向于使用Mac。Mac用户只答对了基础问题的75%,而PC用户却高达83%。