class Person implements Serializable {/*** */private static final long serialVersionUID = 6191069895710625778L;private String name;private int age;private String sex;public Person(){}public Person(String name, int age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";}
}
public class Test {public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {Person man = new Person("obob",18,"M");System.out.println("原始對象:"+man);String filePath = "Person.txt";serialize(man, filePath);Person p = deSerialize(new File(filePath));System.out.println("反序列化后的對象:"+p);}public static void serialize(Person p, String filePath) throws FileNotFoundException, IOException {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(filePath)));oos.writeObject(p);System.out.println("序列化成功");oos.close();}public static Person deSerialize(File file) throws FileNotFoundException, IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));Person p = (Person) ois.readObject();System.out.println("反序列化成功");ois.close();return p;}}輸出為:
原始對象:Person [name=obob, age=18, sex=M]
序列化成功
反序列化成功
反序列化后的對象:Person [name=obob, age=18, sex=M]
3.2 使用Json序列化工具
FastJson、ProtoBuf、Jackson等序列化工具都可以,以fastjson為例
Person man = new Person("obob",18,"M");//序列化String json = JSONObject.toJSONString(man);System.out.println(json);//反序列化System.out.println(JSONObject.parseObject(json, Person.class));