使用xstream实现对JavaBean与xml字符串的互转
近来项目中需要实现javabean与xml文件的互转,一个同事发现了xstream不错。简洁易用,不错的开源组件,在这里推荐一下。并附上使用示例与jar包作为笔记。有需要的同学可以学学。
?
1.Person javabean类
?
public class Person {private String firstname;private String lastname;private PhoneNumber phone;private PhoneNumber fax;public Person() {super();}public Person(String firstname, String lastname) {super();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;}@Overridepublic String toString() {return "Person [firstname=" + firstname + ", lastname=" + lastname+ ", phone=" + phone + ", fax=" + fax + "]";}}
?
2.PhoneNumber javabean类
public class PhoneNumber {private int code;private String number;public PhoneNumber() {super();}public PhoneNumber(int code, String number) {super();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;}@Overridepublic String toString() {return "PhoneNumber [ code =" + code + ", number=" + number + "]";}3.转换测试类import org.junit.Test;import com.thoughtworks.xstream.XStream;public class ConvertTest {/** * 将Person转换成xml字符串 */@Testpublic void personToXML() {XStream xstream = new XStream();xstream.alias("person", Person.class);xstream.alias("phonenumber", PhoneNumber.class);Person joe = new Person("Joe", "Walnes");joe.setPhone(new PhoneNumber(123, "1234-456"));joe.setFax(new PhoneNumber(123, "9999-999"));String xml = xstream.toXML(joe);System.out.println(xml);} //输出结果/* * <person> <firstname>Joe</firstname> <lastname>Walnes</lastname> <phone> <code>123</code> <number>1234-456</number> </phone> <fax> <code>123</code> <number>9999-999</number> </fax></person> *//** * 将xml字符串转换成Person */@Testpublic void xmlToPerson() {String site = "CAN";XStream xstream = new XStream();xstream.alias("person", Person.class);xstream.alias("phonenumber", PhoneNumber.class);String xml = "<person><firstname>Joe</firstname><lastname>Walnes</lastname><phone><code>123</code><number>1234-456</number></phone><fax><code>123</code><number>9999-999</number></fax></person>";xstream.omitField(Person.class, site);Person newJoe = (Person) xstream.fromXML(xml);System.out.println(newJoe.toString());} //输出结果//Person [firstname=Joe, lastname=Walnes, phone=PhoneNumber [ code = 123, number=1234-456], // fax=PhoneNumber [ code =123, number=9999-999]]}?官网:http://xstream.codehaus.org/tutorial.html参考网址:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html?