使用xml进行对象序列化

package com.example.demo01;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import java.util.Date;


/**
* 使用xml进行对象序列化
* @createTime 2020年11月27日 21:08:00
*/
public class TestXMLSerialization {

/**
* @param args
*/
public static void main(String[] args) {

Person person = new Person();
person.setAddress("hangzhou,china");
person.setAge(18);
person.setBirth(new Date());
person.setName("zhangsan");

//将person对象序列化为XML
XStream xStream = new XStream(new DomDriver());
//设置Person类的别名
xStream.alias("person", Person.class);
String personXML = xStream.toXML(person);

//将XML反序列化还原为person对象
Person zhangsan = (Person)xStream.fromXML(personXML);

System.out.println(personXML);
System.out.println(zhangsan.getBirth());

}
}

maven 文件:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.4</version>
</dependency>
posted @ 2020-11-27 21:14  伤心的鸽子  阅读(153)  评论(0编辑  收藏  举报