Xstream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称。今天我们就简单的学习一下xstream的用法。
Xstream的简单实例
项目的结构如下,设计到三个类:
一、maven中添加xstream的依赖
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>
二、java中使用到的javaBean类
- PhoneNumber类:
public class PhoneNumber {
private int code;
private String number; public PhoneNumber(int code, String number) {
this.code = code;
this.number = 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;
}
}
- Person类:
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax; public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
} public String getFirstname() {
return firstname;
} public void setFirstname(String firstname) {
this.firstname = firstname;
} public String getLastname() {
return lastname;
} public void setLastname(String lastname) {
this.lastname = lastname;
} public PhoneNumber getPhone() {
return phone;
} public void setPhone(PhoneNumber phone) {
this.phone = phone;
} public PhoneNumber getFax() {
return fax;
} public void setFax(PhoneNumber fax) {
this.fax = fax;
}
}
三、我们的测试类XstreamMain
public class XstreamMain { public static void main(String[] args) {
XStream xstream = new XStream();
// XStream xstream = new XStream(new StaxDriver()); Person joe = new Person("Liu", "Ling");
joe.setPhone(new PhoneNumber(155, "1234-456"));
joe.setFax(new PhoneNumber(271, "9999-999")); String xml = xstream.toXML(joe);
System.out.println(xml); Person person = (Person) xstream.fromXML(xml);
System.out.println(person.getFirstname()); // Liu
}
}
四、程序的运行结果如下:
<com.linux.huhx.xstream.Person>
<firstname>Liu</firstname>
<lastname>Ling</lastname>
<phone>
<code>155</code>
<number>1234-456</number>
</phone>
<fax>
<code>271</code>
<number>9999-999</number>
</fax>
</com.linux.huhx.xstream.Person>
Liu
如果程序中XstreamMain类加上代码:xstream.alias("person", Person.class); 那么上述的<com.linux.huhx.xstream.Person>会被替换为:<person>