- 浏览: 8668 次
- 性别:
- 来自: 武汉
最新评论
《xStream完美转换XML、JSON》学习笔记
xStream框架
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文件
2,完整的XStreamTest.java文件:
3,运行结果:
4,git源代码地址:
https://git.oschina.net/coderdream/xsteam-demo
5,源代码下载:
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("一班", 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(); } } /** * <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("一班", bean, 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, 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); 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 = 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"); 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, JsonWriter.DROP_ROOT_MODE); } }); xstream.alias("student", 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","birthday":[{},"2010-11-22"]}} // json = "{\"list\": [{" + "\"id\": 1," + "\"name\": \"haha\"," + "\"email\": \"email\"," // + "\"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,源代码下载:
- xsteam-demo.7z (6 KB)
- 下载次数: 0
相关推荐
xStream完美转换XML、JSON,包括XML转换成对象,以及对象转换成XML,以及对象转换成JSON,以及注意事项
标题 "xStream完美转换XML、JSON" 指的是使用xStream库在Java中进行XML与JSON数据格式之间的转换。xStream是一个强大的库,它提供了一种简单的方式来序列化和反序列化Java对象到XML,反之亦然。在这个场景中,它同样...
本篇文章将深入探讨xStream如何实现Java对象与XML和JSON的相互转换,并提供详细的代码示例。 ### 1. xStream的安装与引入 首先,你需要在项目中添加xStream的依赖。如果你使用的是Maven,可以在pom.xml文件中添加...
【xStream 框架详解:Java对象与XML、JSON的完美转换】 xStream是一个强大的Java库,它提供了简单易用的API,用于将Java对象序列化为XML,以及将XML反序列化回Java对象。此外,xStream还支持JSON格式的转换。这个...
XStream在运行时使用Java反射机制对要进行序列化的对象树的结构进行探索,并不需要对对象作出修改。...XStream在进行数据类型转换时,使用系统缺省的类型转换器。同时,也支持用户自定义的类型转换器。
在这个场景中,我们将探讨如何使用XStream将XML文档转换成Java对象,进而转化为JSON对象。 首先,我们需要引入XStream库。XStream的核心功能是能够将Java对象和XML之间的映射自动化,极大地简化了序列化和反序列化...
Xstream和Json是两种广泛使用的工具,分别用于Java对象到XML和JSON格式的转换。本文将深入探讨Xstream库如何与Json进行交互,以及在实际应用中的使用。 Xstream是一个Java库,它提供了简单、高效的方式来序列化和反...
**XStream:JavaBean与XML/JSON之间的转换大师** XStream是一个开源库,它为Java对象提供了简单且直观的XML序列化和反序列化的解决方案。它不仅能够将Java对象转换成XML,反之亦然,还能支持JSON格式的转换。这个...
Xstream 是一个 Java 库,用于处理 XML 文件的序列化和反序列化,同时也支持将 JavaBean 转换为 JSON 格式。它的核心理念是通过简单的 API 设计,使得 XML 序列化过程变得简洁,无需额外的映射文件或辅助类。 ### 1...
通过实践,你会更熟悉如何在各种场景下利用XStream进行对象和XML之间的转换。 总之,XStream是一个强大的工具,可以帮助开发者轻松地在Java对象和XML之间进行转换。其简洁的API和自动类型转换能力使得它在处理序列...
在`xmlAnalysis`文件夹中,可能包含了一个简单的Java程序,演示了如何使用DOM、SAX、StAX和XStream解析XML文件,并展示了XStream如何在JavaBean与XML之间进行转换。你可以运行这些代码,观察输出结果,以加深理解。...
在XML到JSON转换过程中,XStream可能首先用于将XML数据转换为Java对象,然后这些对象再由Json-lib处理成JSON格式。 XML到JSON的转换通常包括以下步骤: - 解析XML文档,将其转换为DOM(Document Object Model)树。...
在Java中,可以使用各种库来实现XML到JSON的转换,其中XStream是一个流行的库,它提供了强大的XML序列化和反序列化功能。XStream虽然主要设计用来XML操作,但也可以通过添加额外的转换器来处理JSON。首先,你需要...
XStream库提供了一个简单、直观的方式来实现这种转换,使得XML序列化和反序列化变得非常方便。本篇将详细介绍XStream如何处理XML与Java对象的相互转换,以及如何处理List、Map等集合类型的数据。 首先,XStream是一...
在这个版本中,XStream提供了对Java Bean对象转换为XML的全面支持。 **XStream的工作原理:** XStream的核心是基于反射的,它通过分析Java对象的类结构来构建XML表示。它使用了一种称为"alias"的概念,允许我们将...
XStream的工作原理是基于反射和类型转换,它可以自动地映射Java类的字段到XML元素,反之亦然。这使得开发者无需编写大量繁琐的代码就能完成XML与Java对象之间的转换。下面我们将深入探讨Xstream的核心概念和使用方法...
XStream是一个强大的库,它使得XML与Java对象之间的转换变得简单。在这个主题中,我们将深入探讨如何使用XStream进行XML与Java对象的互换,并了解其工作原理。 首先,XStream是一个开源库,由Johannes Leutenegger...
- 使用JsonXML Java库:这个库专门用于JSON到XML的转换,提供了简单易用的API。 - Google的Gson库可以通过第三方扩展如`com.thoughtworks.xstream:xstream`实现JSON到XML的转换。 3. Java对象到XML和JSON: - ...