@Override public String toString(){ return String.format("Halo, My name is %s, my sex is %s, " + "my nickName is %s", name, sex, nickName); }
publicstaticvoidmain(String[] args)throws Exception { Person person = new Person("向晚", "girl", "Ava"); System.out.println(String.format("序列化前:%s",person));
//序列化后写入到磁盘里,再读取出来反序列化。添加transient的字段,在序列化时,就已经忽略掉了 File file = new File("C:\\Users\\meethigher\\Desktop\\aaa\\src\\main\\resources\\index.txt"); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file)); os.writeObject(person);
ObjectInputStream is = new ObjectInputStream(new FileInputStream(file)); person = (Person) is.readObject(); System.out.println(String.format("序列化后:%s",person));
//通过fastjson模拟序列化,添加transient的字段不参与序列化 String s = JSON.toJSONString(person); System.out.println(String.format("使用fastjson序列化后的内容:%s",s));
} }
运行结果
1 2 3
序列化前:Halo, My nameis 向晚, my sex is girl, my nickName is Ava 序列化后:Halo, My nameis null, my sex is girl, my nickName is Ava 使用fastjson序列化后的内容:{"nickName":"Ava","sex":"girl"}
publicstaticvoidmain(String[] args){ Person person = new Person("a", "init", "a"); System.out.println(person); Person person1 = new Person("b", "b"); System.out.println(person1); Person person2 = new Person("c", "c"); System.out.println(person2); }
输出结果
1 2 3
Halo, My nameis a, my sex is init, my nickName is a Halo, My nameis b, my sex is init, my nickName is b Halo, My nameis c, my sex is init, my nickName is c
publicstaticvoidmain(String[] args)throws Exception { File file = new File("C:\\Users\\meethigher\\Desktop\\aaa\\src\\main\\resources\\index.txt");
ObjectInputStream is = new ObjectInputStream(new FileInputStream(file)); Person person = (Person) is.readObject(); System.out.println(String.format("序列化后:%s",person)); } }
就能看出,其实static修饰的变量也没有被序列化
1
序列化后:Halo, My nameis null, my sex is null, my nickName is Ava
@Override public String toString(){ return String.format("Halo, My name is %s, my sex is %s, " + "my nickName is %s", name, sex, nickName); }
publicstaticvoidmain(String[] args)throws Exception { Person person = new Person("向晚", "girl", "Ava"); System.out.println(String.format("序列化前:%s", person));
//序列化后写入到磁盘里,再读取出来反序列化。添加transient的字段,在序列化时,就已经忽略掉了 File file = new File("C:\\Users\\meethigher\\Desktop\\aaa\\src\\main\\resources\\index.txt"); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file)); os.writeObject(person);
ObjectInputStream is = new ObjectInputStream(new FileInputStream(file)); person = (Person) is.readObject(); System.out.println(String.format("序列化后:%s", person));
//通过fastjson模拟序列化,添加transient的字段不参与序列化 String s = JSON.toJSONString(person); System.out.println(String.format("使用fastjson序列化后的内容:%s", s));
序列化前:Halo, My nameis 向晚, my sex is girl, my nickName is Ava 序列化后:Halo, My nameis 向晚, my sex is girl, my nickName is Ava 使用fastjson序列化后的内容:{"nickName":"Ava","sex":"girl"}