public class User {
@Expose
private String userName;
@Expose
private String password;
@Expose
private int age;
@Expose
private boolean isStudent;
@Expose
private com.example.simplenotebook.xuliehuahefanxuliehua.bean.Job job;
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public int getAge() {
return age;
}
public boolean isStudent() {
return isStudent;
}
public void setJob(Job job) {
this.job = job;
}
public Job getJob() {
return job;
}
public User(String userName, String password, int age, boolean isStudent) {
this.userName = userName;
this.password = password;
this.age = age;
this.isStudent = isStudent;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", age=" + age +
", isStudent=" + isStudent +
", job=" + job +
'}';
}
}
public class Job {
private String name;
private int salary;
public Job(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "job{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
public class MapUnitTest {
@Test
public void testSet(){
Set<User> set1 = new HashSet<>();//创建set集合
set1.add(new User("Anglin1","123",18,false));
set1.add(new User("Anglin2","123",88,true));
set1.add(null);
//创建Gson提供的gson'对象
Gson gson = new Gson();
//序列化
String json = gson.toJson(set1);
System.out.println("序列化"+json);
//反序列化
Type type = new TypeToken<Set<User>>() {
}.getType();
Set<User> set2 = gson.fromJson(json,type);
//set没有get方法,需要用到迭代器
Iterator<User> iterator = set2.iterator();
while (iterator.hasNext()){
User next = iterator.next();
System.out.println("反序列化"+next);
}
}
}
1.当我们类型里面有一个属性为null的时候gson序列化的时候会忽略掉该属性。
2.如果是集合以及数组里面有属性为null的时候,gson则不会忽略。
如果希望JSON字符串字段名称不以变量名作为key,比如JSON字符串中的key在java里是关键字时,可以借助@SerializedName注解控制JSON字段中的Key命名。