xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;
前面有介绍过json-lib这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html
以及Jackson这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
它们都完美支持JSON,但是对xml的支持还不是很好。一定程度上限制了对Java对象的描述,不能让xml完全体现到对Java对象的描述。这里将会介绍xStream对JSON、XML的完美支持。xStream不仅对XML的转换非常友好,而且提供annotation注解,可以在JavaBean中完成对xml节点、属性的描述。以及对JSON也支持,只需要提供相关的JSONDriver就可以完成转换。
原文地址
xStream完美转换XML、JSON
http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
以下是学习笔记:
1,改造成Maven工程后的pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.coderdream</groupId> <artifactId>xsteam-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>xsteam-demo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.8</version> </dependency> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.3.7</version> </dependency> </dependencies> <build> <finalName>xsteam-demo</finalName> </build> </project>
2,完整的XStreamTest.java文件:
package com.hoo.test; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.codehaus.jettison.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hoo.entity.Birthday; import com.hoo.entity.Classes; import com.hoo.entity.Student; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.json.JsonWriter; /** * <b>function:</b>Java对象和XML字符串的相互转换 jar-lib-version: xstream-1.3.1 * * @author hoojo * @createDate Nov 27,2010 12:15:15 PM * @file XStreamTest.java * @package com.hoo.test * @project WebHttpUtils * @blog http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @version 1.0 */ public class XStreamTest { private XStream xstream = null; private ObjectOutputStream out = null; private ObjectInputStream in = null; private Student bean = null; /** * <b>function:</b>初始化资源准备 * * @author hoojo * @createDate Nov 27,2010 12:16:28 PM */ @Before public void init() { try { xstream = new XStream(); // xstream = new XStream(new DomDriver()); // 需要xpp3 jar } catch (Exception e) { e.printStackTrace(); } bean = new Student(); bean.setAddress("china"); bean.setEmail("jack@email.com"); bean.setId(1); bean.setName("jack"); Birthday day = new Birthday(); day.setBirthday("2010-11-22"); bean.setBirthday(day); } /** * <b>function:</b>释放对象资源 * * @author hoojo * @createDate Nov 27,2010 12:16:38 PM */ @After public void destory() { xstream = null; bean = null; try { if (out != null) { out.flush(); out.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } System.gc(); } public final void fail(String string) { System.out.println(string); } public final void failRed(String string) { System.err.println(string); } @Test public void writeList2XML4Annotation() { try { failRed("---------annotation Bean --> XML---------"); Student stu = new Student(); stu.setName("jack"); Classes c = new Classes("一班",bean,stu); c.setNumber(2); // 对指定的类使用Annotation // xstream.processAnnotations(Classes.class); // 启用Annotation // xstream.autodetectAnnotations(true); xstream.alias("student",Student.class); fail(xstream.toXML(c)); } catch (Exception e) { e.printStackTrace(); } } @Test public void writeList2XML4Annotation2() { try { failRed("---------annotation Bean --> XML---------"); Student stu = new Student(); stu.setName("jack"); Classes c = new Classes("一班",stu); c.setNumber(2); // 对指定的类使用Annotation xstream.processAnnotations(Classes.class); // 启用Annotation xstream.autodetectAnnotations(true); xstream.alias("student",Student.class); fail(xstream.toXML(c)); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>Java Map集合转XML * * @author hoojo * @createDate Nov 27,2010 1:13:26 PM */ @Test public void writeMap2XML() { try { failRed("---------Map --> XML---------"); Map<String,Student> map = new HashMap<String,Student>(); map.put("No.1",bean);// put bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); Birthday day = new Birthday("2010-11-22"); bean.setBirthday(day); map.put("No.2",bean);// put bean = new Student(); bean.setName("jack"); map.put("No.3",bean);// put xstream.alias("student",Student.class); xstream.alias("key",String.class); xstream.useAttributeFor(Student.class,"id"); xstream.useAttributeFor("birthday",String.class); fail(xstream.toXML(map)); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>用OutStream输出流写XML * * @author hoojo * @createDate Nov 27,2010 1:13:48 PM */ @Test public void writeXML4OutStream() { try { out = xstream.createObjectOutputStream(System.out); Student stu = new Student(); stu.setName("jack"); Classes c = new Classes("一班",stu); c.setNumber(2); failRed("---------ObjectOutputStream # JavaObject--> XML---------"); out.writeObject(stu); out.writeObject(new Birthday("2010-05-33")); out.write(22);// byte out.writeBoolean(true); out.writeFloat(22.f); out.writeUTF("hello"); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>用InputStream将XML文档转换成java对象 需要额外的jar xpp3-main.jar * * @author hoojo * @createDate Nov 27,2010 1:14:52 PM */ @Test public void readXML4InputStream() { try { String s = "<object-stream><com.hoo.entity.Student><id>0</id><name>jack</name>" + "</com.hoo.entity.Student><com.hoo.entity.Birthday><birthday>2010-05-33</birthday>" + "</com.hoo.entity.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" + "<string>hello</string></object-stream>"; failRed("---------ObjectInputStream## XML --> javaObject---------"); StringReader reader = new StringReader(s); in = xstream.createObjectInputStream(reader); Student stu = (Student) in.readObject(); Birthday b = (Birthday) in.readObject(); byte i = in.readByte(); boolean bo = in.readBoolean(); float f = in.readFloat(); String str = in.readUTF(); System.out.println(stu); System.out.println(b); System.out.println(i); System.out.println(bo); System.out.println(f); System.out.println(str); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将XML字符串转换成Java对象 * * @author hoojo * @createDate Nov 27,2010 2:39:06 PM */ @SuppressWarnings("unchecked") @Test public void readXml2Object() { try { failRed("-----------Xml >>> Bean--------------"); Student stu = (Student) xstream.fromXML(xstream.toXML(bean)); fail(stu.toString()); List<Student> list = new ArrayList<Student>(); list.add(bean);// add Map<String,bean);// put bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); Birthday day = new Birthday("2010-11-22"); bean.setBirthday(day); list.add(bean);// add map.put("No.2",bean);// put bean = new Student(); bean.setName("jack"); list.add(bean);// add map.put("No.3",bean);// put failRed("==========XML >>> List==========="); List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list)); fail("size:" + studetns.size());// 3 for (Student s : studetns) { fail(s.toString()); } failRed("==========XML >>> Map==========="); Map<String,Student> maps = (Map<String,Student>) xstream.fromXML(xstream.toXML(map)); fail("size:" + maps.size());// 3 Set<String> key = maps.keySet(); Iterator<String> iter = key.iterator(); while (iter.hasNext()) { String k = iter.next(); fail(k + ":" + map.get(k)); } } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON 需要添加jettison jar * * @author hoojo * @createDate Nov 27,2010 1:23:18 PM */ @Test public void writeEntity2JETTSON() { failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString========="); xstream = new XStream(new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student",Student.class); fail(xstream.toXML(bean)); } /** * <b>function:</b>用XStream结合JsonHierarchicalStreamDriver驱动 转换java对象为JSON字符串 * * @author hoojo * @createDate Nov 27,2010 1:16:46 PM */ @Test public void writeEntiry2JSON() { failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); xstream = new XStream(new JsonHierarchicalStreamDriver()); // xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student",Student.class); failRed("-------Object >>>> JSON---------"); fail(xstream.toXML(bean)); // failRed("========JsonHierarchicalStreamDriver==删除根节点========="); // 删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out,JsonWriter.DROP_ROOT_MODE); } }); // xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student",Student.class); fail(xstream.toXML(bean)); } @Test public void writeList2JSON() { failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver(); xstream = new XStream(driver); // xstream = new XStream(new JettisonMappedXmlDriver());//转换错误 // xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student",Student.class); List<Student> list = new ArrayList<Student>(); list.add(bean);// add bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); Birthday day = new Birthday("2010-11-22"); bean.setBirthday(day); list.add(bean);// add bean = new Student(); bean.setName("jack"); list.add(bean);// add fail(xstream.toXML(list)); // failRed("========JsonHierarchicalStreamDriver==删除根节点========="); // 删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out,JsonWriter.DROP_ROOT_MODE); } }); xstream.alias("student",Student.class); fail(xstream.toXML(list)); } @Test public void writeMap2JSON() { failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString========="); xstream = new XStream(new JsonHierarchicalStreamDriver()); // xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("student",Student.class); Map<String,Student>(); map.put("No.1",bean);// put bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); bean.setBirthday(new Birthday("2010-11-21")); map.put("No.2",bean);// put bean = new Student(); bean.setName("jack"); map.put("No.3",bean);// put fail(xstream.toXML(map)); // failRed("========JsonHierarchicalStreamDriver==删除根节点========="); // 删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out,Student.class); fail(xstream.toXML(map)); } /** * <b>function:</b>JsonHierarchicalStreamDriver可以将简单的json字符串转换成java对象,list、map转换不成功; * JsonHierarchicalStreamDriver读取JSON字符串到java对象出错 * * @author hoojo * @createDate Nov 27,2010 1:22:26 PM * @throws JSONException */ @Test public void readJSON2Object() throws JSONException { String json = "{\"student\": {" + "\"id\": 1," + "\"name\": \"haha\"," + "\"email\": \"email\"," + "\"address\": \"address\"," + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "}}"; // JsonHierarchicalStreamDriver读取JSON字符串到java对象出错,但JettisonMappedXmlDriver可以 xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("student",Student.class); fail(xstream.fromXML(json).toString()); // JettisonMappedXmlDriver转换List集合出错,但JsonHierarchicalStreamDriver可以转换正确 // xstream = new XStream(new JsonHierarchicalStreamDriver()); // xstream.alias("student",Student.class); // // // JettisonMappedXmlDriver 转换的字符串 // // {"list":{"student":[{"id":1,"name":"haha","email":"email","address":"address","birthday":[{},"2010-11-22"]}]},"student":{"id":2,"name":"tom","email":"tom@125.com","address":"china","2010-11-22"]}} // json = "{\"list\": [{" + "\"id\": 1," // + "\"address\": \"address\"," + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "},{" // + "\"id\": 2," + "\"name\": \"tom\"," + "\"email\": \"tom@125.com\"," + "\"address\": \"china\"," // + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "}]}"; // System.out.println(json);// 用js转换成功 // List list = (List) xstream.fromXML(json); //System.out.println(list.size());// 0好像转换失败 } }
3,运行结果:
---------annotation Bean --> XML--------- <class 名称="一班"> <Students> <id>1</id> <name>jack</name> <email>jack@email.com</email> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </Students> <Students> <id>0</id> <name>jack</name> </Students> <created>1439030984003</created> </class> ---------ObjectInputStream## XML --> javaObject--------- jack#0#null#null#null 2010-05-33 22 true 22.0 hello ---------ObjectOutputStream # JavaObject--> XML--------- <object-stream> <com.hoo.entity.Student> <id>0</id> <name>jack</name> </com.hoo.entity.Student> <com.hoo.entity.Birthday> <birthday>2010-05-33</birthday> </com.hoo.entity.Birthday> <byte>22</byte> <boolean>true</boolean> <float>22.0</float> <string>hello</string> </object-stream>-----------Xml >>> Bean-------------- ==========XML >>> List=========== ==========XML >>> Map=========== =======JettisonMappedXmlDriver===JavaObject >>>> JaonString========= ---------annotation Bean --> XML--------- ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= -------Object >>>> JSON--------- ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= ---------Map --> XML--------- ======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========
4,git源代码地址:
https://git.oschina.net/coderdream/xsteam-demo 5,源代码下载: 原文链接:https://www.f2er.com/xml/296330.html