本例使用XStream生成一个xml文件,再发序列化xml文件内容。
XStream是一个简单的类库,可以序列化对象到xml,还可以将xml还原为对象。?
XStream官网:http://xstream.codehaus.org/?
附件提供XStream和xpp3相关的jar下载:?
xstream-1.2.2.jar?
xpp3-1.1.3.3_min.jar?
为了使用XStream,需要对其初始化,初始化方法有两种:?
同时这里对mode参数做个简单的说明:?
在XStream序列化或反序列化对象时,它会创建两个类MarshallingContext和UnmarshallingContext,由它们来处理数据,以及委派合适的转换器。XStream提供了三对上下文的缺省实现,它们之间有着细微的差别。缺省值可以通过方法XStream.setMode()来改变,需要传递下面参数中的一个:?
public class Person { private int id; private String name; private int age; private PhoneNumber phone; public int getId() { return id; } public void setId(int id) { this.id = id; } 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 PhoneNumber getPhone() { return phone; } public void setPhone(PhoneNumber phone) { this.phone = phone; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + "]"; } }?PhoneNumber.java
public class PhoneNumber { private int code; private String number; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public String toString() { return "PhoneNumber [code=" + code + ", number=" + number + "]"; } }? 实现功能最主要是下面这个类了: XStreamTest.java
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import com.thoughtworks.xstream.XStream; public class XStreamTest { public static void main(String[] args) throws Exception { Person person = initPerson(); XStream xStream = new XStream(); xStream.alias("person", Person.class); FileOutputStream fileOutputStream=new FileOutputStream(new File("test.xml")); xStream.toXML(person,fileOutputStream); //反序列化 FileInputStream fileInputStream=new FileInputStream(new File("test.xml")); Person person1=(Person)xStream.fromXML(fileInputStream); System.out.println(person1.toString()); } public static Person initPerson(){ Person person = new Person(); person.setId(20); person.setName("huangwei"); person.setAge(24); PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setCode(222); phoneNumber.setNumber("15200000000"); person.setPhone(phoneNumber); return person; } }? 打印生成的xml文件内容如下:
<person> <id>20</id> <name>huangwei</name> <age>24</age> <phone> <code>222</code> <number>15200000000</number> </phone> </person>? 反序列化解过如下:
Person [id=20, name=huangwei, age=24, phone=PhoneNumber [code=222, number=15200000000]]?