网站开发最重要的技巧,seo经理,wordpress 素锦,网站优化平台一、Map的序列化与反序列化
1.Map集合类型对象在反序列化时与List一样#xff0c;需要使用TypeToken完成反序列化。
2.Set在反序列化时需要使用TypeToken完成反序列化。
创建User类和job类
public class User {Exposeprivate String userName;Exposeprivate String passwo…一、Map的序列化与反序列化
1.Map集合类型对象在反序列化时与List一样需要使用TypeToken完成反序列化。
2.Set在反序列化时需要使用TypeToken完成反序列化。
创建User类和job类
public class User {Exposeprivate String userName;Exposeprivate String password;Exposeprivate int age;Exposeprivate boolean isStudent;Exposeprivate 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;}Overridepublic 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;}Overridepublic String toString() {return job{ name name \ , salary salary };}
}
测试代码
public class MapUnitTest {Testpublic void testSet(){SetUser 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 TypeTokenSetUser() {}.getType();SetUser set2 gson.fromJson(json,type);//set没有get方法需要用到迭代器IteratorUser iterator set2.iterator();while (iterator.hasNext()){User next iterator.next();System.out.println(反序列化next);}}}
运行结果 二、变量值为null的序列化与反序列化
1.当我们类型里面有一个属性为null的时候gson序列化的时候会忽略掉该属性。
2.如果是集合以及数组里面有属性为null的时候gson则不会忽略。
三、控制序列化与反序列化的变量名称
如果希望JSON字符串字段名称不以变量名作为key比如JSON字符串中的key在java里是关键字时可以借助SerializedName注解控制JSON字段中的Key命名。