1.使用@Expose可以区分实体中不想被序列化的属性
@Expose标签的2个属性.
serialize
- public
class User { -
- @Expose
- private
String username; - @Expose(serialize=false)
- private
int age ; -
- private
List 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 getList() { - return
list; - }
- public
void setList(List list) { - this.list
= list; - }
-
- public
static void main(String []args){ - User
user = new User("lemon",27); - List
list = new ArrayList(); - 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().excludeFieldsWithoutExpo seAnnotation().create(); - Gson
g2 = new GsonBuilder().excludeFieldsWithoutExpo seAnnotation().create(); - System.out.println(g2.toJson(user));
//{"username":"lemon"} -
} - }
@Expose
@SerializedName("name")
private
String username;
public
static void main(String []args){ User
user = new User("lemon",27); List
list = new ArrayList(); 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().excludeFieldsWithoutExpo seAnnotation().create(); Gson
g2 = new GsonBuilder().excludeFieldsWithoutExpo seAnnotation().create(); //{"name":"lemon"}
System.out.println(g2.toJson(user));
}
补充:简单方式:排除部分不序列化的属性(特别是循环引用的)
可以使用关键字:transient。