程序员人生 网站导航

XStream实现xml和java对象之间的互相转换,同理JSON也可以

栏目:互联网时间:2014-09-24 19:54:40

首先去官网下载响应JAR包

http://xstream.codehaus.org/index.html

最少需要两个jar包,一个xstream.jar,一个是xmlpull.jar

首先来看下java对象到xml的转换

package xml; class PhoneNumber { private int code; private int number; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } } public class Person { private String username; private int age; private PhoneNumber pn; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public PhoneNumber getPn() { return pn; } public void setPn(PhoneNumber pn) { this.pn = pn; } }

以上是一个普通的java对象

package xml; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XmlUtils { private static XStream xs = new XStream(new StaxDriver()); public static String objToXml(Object obj) { //xs.aliasPackage(name, pkgName); return xs.toXML(obj); } public static void main(String[] args) { Person p = new Person(); p.setAge(26); p.setUsername("chiwei"); PhoneNumber pn = new PhoneNumber(); pn.setCode(188); pn.setNumber(67101080); p.setPn(pn); xs.alias("person", Person.class); String xml = objToXml(p); Person per = (Person)xs.fromXML(xml); System.out.println(xml); System.out.println(per.getUsername()); } }

以上代码,先是生成一个对象,给各个属性赋值,然后调用toXML将对象转换为xml格式的普通文本,注意在转换前调用了alias目的是为了将xml.Person重命名为person

<?xml version="1.0" ?><person><username>chiwei</username><age>26</age><pn><code>188</code><number>67101080</number></pn></person>

这里xstream实例化时候传入了StaxDriver表示A driver using the StAX API to create XML reader and writer.

如果你使用xpp3driver,你需要引入该jar包

后面则根据上面转换后的xml继续转换成相应的对象Person

<?xml version="1.0" ?><person><username>chiwei</username><age>26</age><pn><code>188</code><number>67101080</number></pn></person>
chiwei


很简单



















------分隔线----------------------------
------分隔线----------------------------

最新技术推荐