XStream 用法汇总
创建XSteam对象的方式非常easy。仅仅须要new XStream()就可以。
Java到xml。用toXML()方法。
Xml到Java,用fromXML()方法。
在没有不论什么设置默认情况下。java到xml的映射,是java成员名相应xml的元素名。java类的全名相应xml根元素的名字。而实际中,往往是xml和java类都有了,要完毕相互转换,必须进行别名映射。
别名配置包括三种情况:
1、类别名,用alias(String name, Class type)。
2、类成员别名,用aliasField(String alias, Class definedIn, String fieldName)
3、类成员作为属性别名。用 aliasAttribute(Class definedIn, String attributeName, String alias),单独命名没有意义。还要通过useAttributeFor(Class definedIn, String fieldName) 应用到某个类上。
别名的配置是非常重要的。可是当中有些细节问题非常重要,在样例中会专门做具体说明。
另外还有不太经常使用的方法:
addImplicitCollection(Class ownerType, String fieldName),去掉集合类型生成xml的父节点。
registerConverter(Converter converter) 。注冊一个转换器。
假设你的xml非常大。或者为了安全性。以流的方式传输,那么XStream也提供丰富的API,
假设这些主要的操作还不能满足你应用的需求,XStream提供丰富的扩展点。你能够实现自己的转换器。还能够利用XStream完毕更负责的功能,比方输出其它非xml格式的数据,还能够输出html,还支持XML Dom类型数据,这些应用起来略微复杂些。
当然这些不是XStream应用的重点,也不用理会,真正须要的时候再查看API和源代码研究研究。
XStream的长处非常多。可是也有一些小bug。比方在定义别名中的下划线“_”转换为xml后会变成“__”这个符号,非常变态。因此,尽量避免在别名中有用不论什么符号。却是须要下划线的时候,能够考虑有用连接符“-”,这个没有问题。
另外,我们的Java Bean中,经常有一些常量。在转换过程,XStream也会将这些常量转换过去,形成常量的xml节点,这显然不是想要的结果,对于常量字段,就不做转换了。
以下给出一个很典型的并且有用的样例,作为对总结的补充:
import java.util.List; public class Person { private String name; private String age; private Profile profile; private List<Address> addlist; public Person(String name, String age, Profile profile, List<Address> addlist) { this.name = name; this.age = age; this.profile = profile; this.addlist = addlist; } public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", profile=" + profile + ", addlist=" + addlist + '}'; } }
public class Profile { private String job; private String tel; private String remark; public Profile(String job, String tel, String remark) { this.job = job; this.tel = tel; this.remark = remark; } public String toString() { return "Profile{" + "job='" + job + '\'' + ", tel='" + tel + '\'' + ", remark='" + remark + '\'' + '}'; } }
import java.util.List; public class Person { private String name; private String age; private Profile profile; private List<Address> addlist; public Person(String name, String age, Profile profile, List<Address> addlist) { this.name = name; this.age = age; this.profile = profile; this.addlist = addlist; } public String toString() { return "Person{" + "name='" + name + '\'' + ", age='" + age + '\'' + ", profile=" + profile + ", addlist=" + addlist + '}'; } }
import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class TestXStream { public static void main(String args[]) { Address address1 = new Address("郑州市经三路", "450001"); Address address2 = new Address("北京市海淀区", "100000"); List<Address> addList = new ArrayList<Address>(); addList.add(address1); addList.add(address2); Profile profile = new Profile("软件project师", "13051594850", "备注说明"); Person person = new Person("X-rapido", "22", profile, addList); // 转换装配 XStream xStream = new XStream(new DomDriver()); /************** 设置类别名。不设默认类全路径 ****************/ xStream.alias("PERSON", Person.class); xStream.alias("PROFILE", Profile.class); xStream.alias("ADDRESS", Address.class); String xml = xStream.toXML(person); System.out.println("----------------第1次输出, 设置类别名---------------- \n"+ xml + "\n"); /************* 设置类成员的别名 ***************/ // 设置Person类的name成员别名Name xStream.aliasField("Name", Person.class, "name"); /* * [注意] 设置Person类的profile成员别名PROFILE,这个别名和Profile类的别名一致, * 这样能够保持XStream对象能够从profile成员生成的xml片段直接转换为Profile成员, * 假设成员profile的别名和Profile的别名不一致,则profile成员生成的xml片段不可 * 直接转换为Profile对象,须要又一次创建XStream对象,这岂不给自己找麻烦? */ xStream.aliasField("PROFILE", Person.class, "profile"); xStream.aliasField("ADDLIST", Person.class, "addlist"); xStream.aliasField("Add", Address.class, "add"); xStream.aliasField("Job", Profile.class, "job"); String xml2 = xStream.toXML(person); System.out.println("----------------第2次输出, 设置类、字段别名---------------- \n"+ xml2 + "\n"); /******* 设置类成员为xml一个元素上的属性 *******/ xStream.useAttributeFor(Address.class, "zipcode"); /************* 设置属性的别名 ***************/ xStream.aliasAttribute(Address.class, "zipcode", "Zipcode"); String xml3 = xStream.toXML(person); System.out.println("----------------第3次输出, 设置类、字段别名,并在xml字段节点上添加属性---------------- \n"+ xml3 + "\n"); /************* 将xml转为java对象 ******× ****/ String person_xml = "<PERSON>\n" + " <Name>熔岩</Name>\n" + " <age>27</age>\n" + " <PROFILE>\n" + " <Job>软件project师</Job>\n" + " <tel>13512129933</tel>\n" + " <remark>备注说明</remark>\n" + " </PROFILE>\n" + " <ADDLIST>\n" + " <ADDRESS Zipcode=\"450001\">\n" + " <Add>郑州市经三路</Add>\n" + " </ADDRESS>\n" + " <ADDRESS Zipcode=\"710002\">\n" + " <Add>西安市雁塔路</Add>\n" + " </ADDRESS>\n" + " </ADDLIST>\n" + "</PERSON>"; String profile_xml = "<PROFILE>\n" + " <Job>软件project师</Job>\n" + " <tel>13512129933</tel>\n" + " <remark>备注说明</remark>\n" + " </PROFILE>"; String address_xml = "<ADDRESS Zipcode=\"710002\">\n" + " <Add>西安市雁塔路</Add>\n" + " </ADDRESS>"; // 相同使用上面的XStream对象将xml转换为Java对象 System.out.println(xStream.fromXML(person_xml).toString()); System.out.println(xStream.fromXML(profile_xml).toString()); System.out.println(xStream.fromXML(address_xml).toString()); } }xStream.toXML()和xStream.fromXML()的经常用法
比方写入文件方法
FileOutputStream fs = new FileOutputStream("d:/employeedata.txt"); xs.toXML(e, fs);读取
public static void main(String[] args) { XStream xs = new XStream(new DomDriver()); Employee e = new Employee(); try { FileInputStream fis = new FileInputStream("d:/employeedata.txt"); xs.fromXML(fis, e); // 打印从对象已被读取的数据 System.out.println(e.toString()); } catch (FileNotFoundException ex) { ex.printStackTrace(); } }
public static void main(String[] args) { Employee e = new Employee(); e.setName("X-rapido"); e.setDesignation("Manager"); e.setDepartment("法国"); XStream xs = new XStream(); try { FileOutputStream fs = new FileOutputStream("d:/employeedata.txt"); xs.toXML(e, fs); System.out.println("XML写入成功"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } }
在实际中。类的属性非常多,嵌套层次也非常复杂。假设只使用XStream原生API来硬编码设置别名等属性。显得太生硬也难以维护。全然能够考虑通过一个xml配置文件来定义全部用到的类的别名定义(包含其成员),然后,通过读取配置构建一个XStream的工厂,在用到时候直接去取。而不是让有用者组装。
我眼下的一个项目中,就是这么实现的,效果非常的好。
以下我给出针对上面提出的问题一个解决方式:
思想:考虑做一个过滤器,在xml转java之前。在Java转xml之后。应用这个过滤器。
这个过滤器提供将xml中的“__”替换为“-”,而且将xml中的不须要的节点剔除。
在过滤之前。我实现了个转换器装配,这一步通过xml来配置,并在java中获取。
代码就省略了。这一步非常灵活,关键看你的应用了。
// 解决XStream对出现双下划线的bug XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));为了能过滤xml。我们须要用Dom4j递归遍历xml文档。以下一些算法代码:
//递归算法:遍历配置文件,找出全部有效的xpath private static void recursiveElement(Element element) { List<Element> elements = element.elements(); validXPathList.add(element.getPath()); if (elements.size() == 0) { //没有子元素 } else { //有子元素 for (Iterator<Element> it = elements.iterator(); it.hasNext();) { //递归遍历 recursiveElement(it.next()); } } } //递归算法:遍历xml,标识无效的元素节点 private static void recursiveFixElement(Element element) { List<Element> elements = element.elements(); if (!validXPathList.contains(element.getPath())) { element.addAttribute("delete", "true"); } if (elements.size() == 0) { //没有子元素 } else { //有子元素 for (Iterator<Element> it = elements.iterator(); it.hasNext();) { Element e = it.next(); if (!validXPathList.contains(e.getPath())) { e.addAttribute("delete", "true"); } //递归遍历 recursiveFixElement(e); } } } /** * 过滤器接口方法,转换不规范字符,剔除无效节点 * * @param xmlStr 要过滤的xml * @return 符合转换器要求的xml */ public static String filter(String xmlStr) { Document document = null; try { document = DocumentHelper.parseText(xmlStr.replaceAll("__", "_")); //递归的调用:标记要剔除的xml元素 recursiveFixElement(document.getRootElement()); List<Node> nodeList = document.selectNodes("//@delete"); for (Node node : nodeList) { node.getParent().detach(); //剔除xml元素 } } catch (DocumentException e) { System.out.println(e.getMessage()); e.printStackTrace(); } return document.asXML(); }输出内容例如以下
----------------第1次输出, 设置类别名---------------- <PERSON> <name>X-rapido</name> <age>22</age> <profile> <job>软件project师</job> <tel>13051594850</tel> <remark>备注说明</remark> </profile> <addlist> <ADDRESS> <add>郑州市经三路</add> <zipcode>450001</zipcode> </ADDRESS> <ADDRESS> <add>北京市海淀区</add> <zipcode>100000</zipcode> </ADDRESS> </addlist> </PERSON> ----------------第2次输出, 设置类、字段别名---------------- <PERSON> <Name>X-rapido</Name> <age>22</age> <PROFILE> <Job>软件project师</Job> <tel>13051594850</tel> <remark>备注说明</remark> </PROFILE> <ADDLIST> <ADDRESS> <Add>郑州市经三路</Add> <zipcode>450001</zipcode> </ADDRESS> <ADDRESS> <Add>北京市海淀区</Add> <zipcode>100000</zipcode> </ADDRESS> </ADDLIST> </PERSON> ----------------第3次输出, 设置类、字段别名,并在xml字段节点上添加属性---------------- <PERSON> <Name>X-rapido</Name> <age>22</age> <PROFILE> <Job>软件project师</Job> <tel>13051594850</tel> <remark>备注说明</remark> </PROFILE> <ADDLIST> <ADDRESS Zipcode="450001"> <Add>郑州市经三路</Add> </ADDRESS> <ADDRESS Zipcode="100000"> <Add>北京市海淀区</Add> </ADDRESS> </ADDLIST> </PERSON> Person{name='熔岩', age='27', profile=Profile{job='软件project师', tel='13512129933', remark='备注说明'}, addlist=[Address{add='郑州市经三路', zipcode='450001'}, Address{add='西安市雁塔路', zipcode='710002'}]} Profile{job='软件project师', tel='13512129933', remark='备注说明'} Address{add='西安市雁塔路', zipcode='710002'}转换装配方式有几种,比方上面代码中使用是DomDriver方式,也有StaxDriver方式,等默认XppDriver方式。可是xpp方式常常解析xml会出错,比方将上面的代码改动
// 转换装配 // XStream xStream = new XStream(new DomDriver()); XStream xStream = new XStream(new StaxDriver());解析的输出就变成下面结果
----------------第1次输出, 设置类别名---------------- <?xml version="1.0" ?><PERSON><name>X-rapido</name><age>22</age><profile><job>软件project师</job><tel>13051594850</tel><remark>备注说明</remark></profile><addlist><ADDRESS><add>郑州市经三路</add><zipcode>450001</zipcode></ADDRESS><ADDRESS><add>北京市海淀区</add><zipcode>100000</zipcode></ADDRESS></addlist></PERSON> ----------------第2次输出, 设置类、字段别名---------------- <?xml version="1.0" ?><PERSON><Name>X-rapido</Name><age>22</age><PROFILE><Job>软件project师</Job><tel>13051594850</tel><remark>备注说明</remark></PROFILE><ADDLIST><ADDRESS><Add>郑州市经三路</Add><zipcode>450001</zipcode></ADDRESS><ADDRESS><Add>北京市海淀区</Add><zipcode>100000</zipcode></ADDRESS></ADDLIST></PERSON> ----------------第3次输出, 设置类、字段别名,并在xml字段节点上添加属性---------------- <?xml version="1.0" ?><PERSON><Name>X-rapido</Name><age>22</age><PROFILE><Job>软件project师</Job><tel>13051594850</tel><remark>备注说明</remark></PROFILE><ADDLIST><ADDRESS Zipcode="450001"><Add>郑州市经三路</Add></ADDRESS><ADDRESS Zipcode="100000"><Add>北京市海淀区</Add></ADDRESS></ADDLIST></PERSON> Person{name='熔岩', age='27', profile=Profile{job='软件project师', tel='13512129933', remark='备注说明'}, addlist=[Address{add='郑州市经三路', zipcode='450001'}, Address{add='西安市雁塔路', zipcode='710002'}]} Profile{job='软件project师', tel='13512129933', remark='备注说明'} Address{add='西安市雁塔路', zipcode='710002'}
Java转换JSON
xStream对JSON也有很好的支持。它提供了2个模型驱动。
用这2个驱动能够完毕Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,须要加入jettison.jar。JSON的转换和XML的转换使用方法一样。仅仅是创建XStream须要传递一个參数,这个參数就是xml到JSON映射转换的驱动。
这里会讲到两个驱动,各自是JettisonMappedXmlDriver、JsonHierarchicalStreamDriver。
1、 用JettisonMappedXmlDriver转换
public static void main(String args[]) { Address address1 = new Address("郑州市经三路", "450001"); Address address2 = new Address("北京市海淀区", "100000"); List<Address> addList = new ArrayList<Address>(); addList.add(address1); addList.add(address2); Profile profile = new Profile("软件project师", "13051594850", "备注说明"); Person person = new Person("X-rapido", "22", profile, addList); XStream xStreamJ = new XStream(new JettisonMappedXmlDriver()); xStreamJ.setMode(XStream.NO_REFERENCES); xStreamJ.alias("person", Person.class); xStreamJ.alias("profile", Profile.class); xStreamJ.alias("address", Address.class); String xml = xStreamJ.toXML(person); System.out.println("JSON:"+ xml); }
{"person":{"name":"X-rapido","age":22,"profile":{"job":"软件project师","tel":13051594850,"remark":"备注说明"},"addlist":[{"address":[{"add":"郑州市经三路","zipcode":450001},{"add":"北京市海淀区","zipcode":100000}]}]}}
2、 用JsonHierarchicalStreamDriver转换
public static void main(String args[]) { Address address1 = new Address("郑州市经三路", "450001"); Address address2 = new Address("北京市海淀区", "100000"); List<Address> addList = new ArrayList<Address>(); addList.add(address1); addList.add(address2); Profile profile = new Profile("软件project师", "13051594850", "备注说明"); Person person = new Person("X-rapido", "22", profile, addList); XStream xStreamJ = new XStream(new JsonHierarchicalStreamDriver()); xStreamJ.alias("person", Person.class); xStreamJ.alias("profile", Profile.class); xStreamJ.alias("address", Address.class); String xml = xStreamJ.toXML(person); System.out.println("JSON:"+ xml); }
JSON:{"person": { "name": "X-rapido", "age": "22", "profile": { "job": "软件project师", "tel": "13051594850", "remark": "备注说明" }, "addlist": [ { "add": "郑州市经三路", "zipcode": "450001" }, { "add": "北京市海淀区", "zipcode": "100000" } ] }}
使用JsonHierarchicalStreamDriver转换默认会给转换后的对象加入一个根节点,可是在构建JsonHierarchicalStreamDriver驱动的时候。你能够重写createWriter方法,删掉根节点。
看上面的结果,一个是默认带根节点的JSON对象,它仅仅是将类名作为一个属性。将对象作为该属性的一个值。而还有一个没有带根属性的JSON就是通过重写createWriter方法完毕的。
添加上面代码。返回没有根节点JSON
//删除根节点 xStreamJ = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); } });
JSON:{ "name": "X-rapido", "age": "22", "profile": { "job": "软件project师", "tel": "13051594850", "remark": "备注说明" }, "addlist": [ { "add": "郑州市经三路", "zipcode": "450001" }, { "add": "北京市海淀区", "zipcode": "100000" } ] }
将JSON转换java对象
public static void main(String args[]) { Address address1 = new Address("郑州市经三路", "450001"); Address address2 = new Address("北京市海淀区", "100000"); List<Address> addList = new ArrayList<Address>(); addList.add(address1); addList.add(address2); Profile profile = new Profile("软件project师", "13051594850", "备注说明"); Person person = new Person("X-rapido", "22", profile, addList); String json = "{\"person\":{\"name\":\"X-rapido\",\"age\":22,\"profile\":{\"job\":\"软件project师\",\"tel\":13051594850,\"remark\":\"备注说明\"},\"addlist\":[{\"address\":[{\"add\":\"郑州市经三路\",\"zipcode\":450001},{\"add\":\"北京市海淀区\",\"zipcode\":100000}]}]}}"; XStream xStreamJ = new XStream(new JettisonMappedXmlDriver()); xStreamJ.alias("person", Person.class); xStreamJ.alias("profile", Profile.class); xStreamJ.alias("address", Address.class); person = (Person) xStreamJ.fromXML(json); System.out.println(person.toString()); }
Person{name='X-rapido', age='22', profile=Profile{job='软件project师', tel='13051594850', remark='备注说明'}, addlist=[Address{add='郑州市经三路', zipcode='450001'}, Address{add='北京市海淀区', zipcode='100000'}]}
以上举例使用的JavaBean对象,对于Map,List对象也是通用的,具有相同功能的还有JsonLib包
XStream还提供了注解放方式。比方在字段上添加@XStreamOmitField表示忽略该字段。等等,这里就不做解说了
演示样例代码下载地址:http://download.csdn.net/detail/xiaokui_wingfly/8800295
参考:http://www.jb51.net/article/14542.htm 、http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html