XStream对象相当Java对象和XML之间的转换器,转换过程是双向的。创建XSteam对象的方式很简单,只需要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 addlist;
-
- public Person(String name, String age, Profile profile, List 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 addlist;
-
- public Person(String name, String age, Profile profile, List 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 addList = new ArrayList();
- addList.add(address1);
- addList.add(address2);
- Profile profile = new Profile("软件工程师", "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");
-
-
-
- xStream.aliasField("Name", Person.class, "name");
-
-
-
-
-
-
- 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");
-
-
-
- xStream.useAttributeFor(Address.class, "zipcode");
-
- xStream.aliasAttribute(Address.class, "zipcode", "Zipcode");
-
- String xml3 = xStream.toXML(person);
- System.out.println("----------------第3次输出, 设置类、字段别名,并在xml字段节点上增加属性---------------- \n"+ xml3 + "\n");
-
-
-
- String person_xml = "\n" +
- " 熔岩\n" +
- " 27\n" +
- " \n" +
- " 软件工程师\n" +
- " 13512129933\n" +
- " 备注说明\n" +
- " \n" +
- " \n" +
- " \n" +
- " 郑州市经三路\n" +
- " \n" +
- " \n" +
- " 西安市雁塔路\n" +
- " \n" +
- " \n" +
- "";
- String profile_xml = "\n" +
- " 软件工程师\n" +
- " 13512129933\n" +
- " 备注说明\n" +
- " ";
- String address_xml = "\n" +
- " 西安市雁塔路\n" +
- " ";
-
-
- 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文档。下面一些算法代码:
-
- private static void recursiveElement(Element element) {
- List elements = element.elements();
- validXPathList.add(element.getPath());
- if (elements.size() == 0) {
-
- } else {
-
- for (Iterator it = elements.iterator(); it.hasNext();) {
-
- recursiveElement(it.next());
- }
- }
- }
-
-
- private static void recursiveFixElement(Element element) {
- List elements = element.elements();
- if (!validXPathList.contains(element.getPath())) {
- element.addAttribute("delete", "true");
- }
- if (elements.size() == 0) {
-
- } else {
-
- for (Iterator it = elements.iterator(); it.hasNext();) {
- Element e = it.next();
- if (!validXPathList.contains(e.getPath())) {
- e.addAttribute("delete", "true");
- }
-
- recursiveFixElement(e);
- }
- }
- }
-
-
-
-
-
-
-
- public static String filter(String xmlStr) {
- Document document = null;
- try {
- document = DocumentHelper.parseText(xmlStr.replaceAll("__", "_"));
-
- recursiveFixElement(document.getRootElement());
- List nodeList = document.selectNodes("//@delete");
- for (Node node : nodeList) {
- node.getParent().detach();
- }
- } catch (DocumentException e) {
- System.out.println(e.getMessage());
- e.printStackTrace();
- }
- return document.asXML();
- }
输出内容如下
- ----------------第1次输出, 设置类别名----------------
-
- X-rapido
- 22
-
- 软件工程师
- 13051594850
- 备注说明
-
-
-
- 郑州市经三路
- 450001
-
-
- 北京市海淀区
- 100000
-
-
-
-
- ----------------第2次输出, 设置类、字段别名----------------
-
- X-rapido
- 22
-
- 软件工程师
- 13051594850
- 备注说明
-
-
-
- 郑州市经三路
- 450001
-
-
- 北京市海淀区
- 100000
-
-
-
-
- ----------------第3次输出, 设置类、字段别名,并在xml字段节点上增加属性----------------
-
- X-rapido
- 22
-
- 软件工程师
- 13051594850
- 备注说明
-
-
-
- 郑州市经三路
-
-
- 北京市海淀区
-
-
-
-
- Person{name='熔岩', age='27', profile=Profile{job='软件工程师', tel='13512129933', remark='备注说明'}, addlist=[Address{add='郑州市经三路', zipcode='450001'}, Address{add='西安市雁塔路', zipcode='710002'}]}
- Profile{job='软件工程师', tel='13512129933', remark='备注说明'}
- Address{add='西安市雁塔路', zipcode='710002'}
转换装配方式有几种,比如上面代码中使用是DomDriver方式,也有StaxDriver方式,等默认XppDriver方式,但是xpp方式经常解析xml会出错,比如将上面的代码修改
-
-
- XStream xStream = new XStream(new StaxDriver());
解析的输出就变成以下结果
- ----------------第1次输出, 设置类别名----------------
- X-rapido22软件工程师13051594850备注说明郑州市经三路450001北京市海淀区100000
-
- ----------------第2次输出, 设置类、字段别名----------------
- X-rapido22软件工程师13051594850备注说明郑州市经三路450001北京市海淀区100000
-
- ----------------第3次输出, 设置类、字段别名,并在xml字段节点上增加属性----------------
- X-rapido22软件工程师13051594850备注说明郑州市经三路北京市海淀区
-
- Person{name='熔岩', age='27', profile=Profile{job='软件工程师', tel='13512129933', remark='备注说明'}, addlist=[Address{add='郑州市经三路', zipcode='450001'}, Address{add='西安市雁塔路', zipcode='710002'}]}
- Profile{job='软件工程师', 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 addList = new ArrayList();
- addList.add(address1);
- addList.add(address2);
- Profile profile = new Profile("软件工程师", "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":"软件工程师","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 addList = new ArrayList();
- addList.add(address1);
- addList.add(address2);
- Profile profile = new Profile("软件工程师", "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": "软件工程师",
- "tel": "13051594850",
- "remark": "备注说明"
- },
- "addlist": [
- {
- "add": "郑州市经三路",
- "zipcode": "450001"
- },
- {
- "add": "北京市海淀区",
- "zipcode": "100000"
- }
- ]
- }}
使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,你可以重写createWriter方法,删掉根节点。
看上面的结果,一个是默认带根节点的JSON对象,它只是将类名作为一个属性,将对象作为该属性的一个值。而另一个没有带根属性的JSON就是通过重写createWriter方法完成的。
增加上面代码,返回没有根节点JSON
-
- StreamJ = 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": "软件工程师",
- "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 addList = new ArrayList();
- addList.add(address1);
- addList.add(address2);
- Profile profile = new Profile("软件工程师", "13051594850", "备注说明");
- Person person = new Person("X-rapido", "22", profile, addList);
-
- String json = "{\"person\":{\"name\":\"X-rapido\",\"age\":22,\"profile\":{\"job\":\"软件工程师\",\"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='软件工程师', 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
转载地址:http://blog.csdn.net/xiaokui_wingfly/article/details/46470145