前言
本文介绍利用java转换xml和java对象
本文测试使用maven项目,项目中需要加入如下依赖:
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
对象代码
@Data
public class Person {
private String firstname;
private String lastname;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
private PhoneNumber phone;
private PhoneNumber 邮件;
}
@Data
public class PhoneNumber {
private int code;
private String number;
public PhoneNumber(int code, String number) {
this.code = code;
this.number = number;
}
}
转换代码
public class XmlUtil {
public String obj2String(Object obj){
XStream xstream = new XStream();
String xml = xstream.toXML(obj);
return xml;
}
public Object string2Obj(String str){
XStream xstream = new XStream();
return xstream.fromXML(str);
}
public static void main(String[] args) {
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.set邮件(new PhoneNumber(123, "9999-999"));
XmlUtil xmlUtil = new XmlUtil();
//对象转换成为xml
String xml = xmlUtil.obj2String(joe);
System.out.println(xml);
//xml转换成为对象
Person newJoe = (Person)xmlUtil.string2Obj(xml);
System.out.println("new Joe:"+newJoe.getFirstname()+" "+newJoe.getLastname());
}
}