1.使用@Expose可以区分实体中不想被序列化的属性
@Expose标签的2个属性.
1.1deserialize
(boolean)反序列化 默认 true1.2
serialize
(boolean)序列化 默认 true使用newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();创建Gson对象,没有@Expose注释的属性将不会被序列化
- publicclassUser{
- @Expose
- privateStringusername;
- @Expose(serialize=false)
- privateintage;
- privateListlist;
- publicUser(Stringusername,intage){
- super();
- this.username=username;
- this.age=age;
- }
- publicStringgetUsername(){
- returnusername;
- }
- publicvoidsetUsername(Stringusername){
- this.username=username;
- }
- publicintgetAge(){
- returnage;
- }
- publicvoidsetAge(intage){
- this.age=age;
- }
- publicListgetList(){
- returnlist;
- }
- publicvoidsetList(Listlist){
- this.list=list;
- }
- publicstaticvoidmain(String[]args){
- Useruser=newUser("lemon",27);
- Listlist=newArrayList();
- list.add("l1");
- list.add("l2");
- user.setList(list);
- Gsong1=newGson();
- //使用newGson();
- System.out.println(g1.toJson(user));//{"username":"lemon","age":27,"list":["l1","l2"]}
- //使用newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
- Gsong2=newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
- System.out.println(g2.toJson(user));//{"username":"lemon"}
- }
- }
@Expose
@SerializedName("name")
privateStringusername;
publicstaticvoidmain(String[]args){
Useruser=newUser("lemon",27);
Listlist=newArrayList();
list.add("l1");
list.add("l2");
user.setList(list);
Gsong1=newGson();
//使用newGson();
//{"name":"lemon","age":27,"list":["l1","l2"]}
System.out.println(g1.toJson(user));
//使用newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gsong2=newGsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
//{"name":"lemon"}
System.out.println(g2.toJson(user));
}
补充:简单方式:排除部分不序列化的属性(特别是循环引用的)可以使用关键字:transient。