- 浏览: 197855 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (121)
- java_基础 (26)
- java_web (15)
- javascript (9)
- extJS (0)
- dwr (0)
- guobin_ETL (1)
- guobin_ssh (17)
- guobin_webservice (1)
- guobin_jbpm (0)
- guobin_jquery (0)
- guobin_acegi (1)
- guobin_poi/jxl (2)
- guobin_multiThread (0)
- guobin_名称解释 (0)
- guobin_FLEX (0)
- guobin_php (0)
- guobin_ORACLE (1)
- guobin_mysql (0)
- guobin_linux (0)
- guobin_powerDesigner (0)
- guobin_visol (0)
- guobin_ER/STUDIO (0)
- guobin_jmesa (0)
- guobin_weblogic (0)
- guobin_kettle (0)
- guobin_一路风雨 (5)
- guobin_spark (0)
- java_xml (7)
- guobin_规则引擎 (0)
- 插件开发 (2)
- 软件管理 (3)
- spring mvc (2)
- java_jni (1)
- eclipse (1)
- oracle (0)
- 项目学习笔记 (1)
- java多线程学习记录 (9)
- websphere性能设置和日常维护 (2)
- (1)
- 系统软件架构设计 (1)
- ces (1)
- 需求分析 (2)
- IBM-CICS GATEWAY (1)
- 工具使用 (1)
- 网络信息安全编程 (1)
最新评论
-
yzh__:
学习一个
Hibernate 自关联注解方式 -
xiaoyahuang:
"2)将Sysdeo Plugin下的DevLoad ...
eclipse项目引用 -
guobin6125:
guobin6125 写道sfasshahhah评论的评论
欢迎使用Kit! -
guobin6125:
sfass
欢迎使用Kit! -
guobin6125:
tst23
欢迎使用Kit!
http://xstream.codehaus.org
XStream是一个序列化对象为XML或XML转换为对象的库.
特点:
简化的API;
无映射文件;
高性能,低内存占用;
整洁的XML;
不需要修改对象;支持内部私有字段,不需要setter/getter方法,final字段;非公有类,内部类;类不需要默认构造器,完全对象图支持.维护对象引用计数,循环引用. i
提供序列化接口;
自定义转换类型策略;
详细的错误诊断;
快速输出格式;当前支持 JSON 和 morphing.
使用场景
Transport 转换
Persistence 持久化对象
Configuration 配置
Unit Tests 单元测试
限制
enhanced 模式: JDK版本 不能<1.5.
虽然预处理注解是安全的,但自动侦查注解可能发生竞争条件.
两分钟简单教程
http://xstream.codehaus.org/tutorial.html
XML解析器
1. XPP3 (需要 xpp3-[version].jar)
XStream xstream = new XStream(new XppDriver());
2. JAXP DOM
XStream xstream = new XStream(new DomDriver());
类型别名Alias
XStream 默认使用完全限制类名作为XML的元素名称.通过使用别名可修改元素名称为指定名称.
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
字段别名
Stream 默认使用字段名, 优先级高于类型.
集合字段中的对象默认使用类型别名.
xstream.aliasField("phonenumber", Person.class, "phone");
注意: Person.class 是包含此字段的类,而不是字段的类型.字段是phone, 别名是phonenumber. 下面也是如此.
序列化与反序列化
对象不需要实现序列化接口. 反序列的对象与原对象不是同一对象.
String xml = xstream.toXML(obj);
T obj = (T)xstream.fromXML(xml);
隐式集合
当我们使用集合类时不想显示集合,只显示里面的元素即可.
使用隐式集合前:
<list>
<element />
<element />
<list>
使用隐式集合:
xstream.addImplicitCollection(Person.class, "list");
使用隐式集合后:
<element />
<element />
XML属性
将类的字段转换成类映射元素的一个属性,而不是元素.
xstream.useAttributeFor(Blog.class, "author");
xstream.registerConverter(new AuthorConverter()); // 注册将对象转换成字符串的转换类.
class AuthorConverter implements SingleValueConverter {
public String toString(Object obj) {
return ((Author) obj).getName();
}
public Object fromString(String name) {
return new Author(name);
}
public boolean canConvert(Class type) {
return type.equals(Author.class);
}
}
SingleValueConverter 转换成简单字符串
Converter 转换成对象
包别名
xstream.aliasPackage("my.company", "org.thoughtworks");
注解
@XStreamAlias("message") 别名注解
作用目标: 类,字段
@XStreamImplicit 隐式集合
@XStreamImplicit(itemFieldName="part")
作用目标: 集合字段
@XStreamConverter(SingleValueCalendarConverter.class) 注入转换器
作用目标: 对象
@XStreamAsAttribute 转换成属性
作用目标: 字段
@XStreamOmitField 忽略字段
作用目标: 字段
Auto-detect Annotations 自动侦查注解
xstream.autodetectAnnotations(true);
自动侦查注解与XStream.processAnnotations(Class[] cls)的区别在于性能.自动侦查注解将缓存所有类的类型.
对象流
bjectOutputStream out = xstream.createObjectOutputStream(someWriter);
ObjectInputStream in = xstream.createObjectInputStream(someReader);
持久化对象
public void persist(String dir, List objects)
{
PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));
List<?> list = new XmlArrayList(strategy);
list.addAll(objects);
}
JSON
解析器:
Jettison StAX
XStreamFacade.java
------------
扩展:
1.
XBird
2.
XStream.XPATH_RELATIVE_REFERENCES
(Default) Uses relative XPath references to signify duplicate references. This produces XML with the least clutter.
XStream.XPATH_ABSOLUTE_REFERENCES
Uses absolute XPath references to signify duplicate references. This might produce for some situations better readable XML. Note, that XStream will read XML with relative paths as well as with absolute paths independent of the XPATH mode.
XStream.ID_REFERENCES
Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this is easier to work with.
XStream.NO_REFERENCES
This disables object graph support and treats the object structure like a tree. Duplicate references are treated as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than the other two modes.
3.
转换器
示例
XStreamFacade.java
EnhancedModeReflectProvider.java
ExampleMessageBody.java
TestXStream.java
说明:
1. 静态字段其实没有必要序列化.
2. 集合类型通常需要进行初始化.
XStream是一个序列化对象为XML或XML转换为对象的库.
特点:
简化的API;
无映射文件;
高性能,低内存占用;
整洁的XML;
不需要修改对象;支持内部私有字段,不需要setter/getter方法,final字段;非公有类,内部类;类不需要默认构造器,完全对象图支持.维护对象引用计数,循环引用. i
提供序列化接口;
自定义转换类型策略;
详细的错误诊断;
快速输出格式;当前支持 JSON 和 morphing.
使用场景
Transport 转换
Persistence 持久化对象
Configuration 配置
Unit Tests 单元测试
限制
enhanced 模式: JDK版本 不能<1.5.
虽然预处理注解是安全的,但自动侦查注解可能发生竞争条件.
两分钟简单教程
http://xstream.codehaus.org/tutorial.html
XML解析器
1. XPP3 (需要 xpp3-[version].jar)
XStream xstream = new XStream(new XppDriver());
2. JAXP DOM
XStream xstream = new XStream(new DomDriver());
类型别名Alias
XStream 默认使用完全限制类名作为XML的元素名称.通过使用别名可修改元素名称为指定名称.
xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);
字段别名
Stream 默认使用字段名, 优先级高于类型.
集合字段中的对象默认使用类型别名.
xstream.aliasField("phonenumber", Person.class, "phone");
注意: Person.class 是包含此字段的类,而不是字段的类型.字段是phone, 别名是phonenumber. 下面也是如此.
序列化与反序列化
对象不需要实现序列化接口. 反序列的对象与原对象不是同一对象.
String xml = xstream.toXML(obj);
T obj = (T)xstream.fromXML(xml);
隐式集合
当我们使用集合类时不想显示集合,只显示里面的元素即可.
使用隐式集合前:
<list>
<element />
<element />
<list>
使用隐式集合:
xstream.addImplicitCollection(Person.class, "list");
使用隐式集合后:
<element />
<element />
XML属性
将类的字段转换成类映射元素的一个属性,而不是元素.
xstream.useAttributeFor(Blog.class, "author");
xstream.registerConverter(new AuthorConverter()); // 注册将对象转换成字符串的转换类.
class AuthorConverter implements SingleValueConverter {
public String toString(Object obj) {
return ((Author) obj).getName();
}
public Object fromString(String name) {
return new Author(name);
}
public boolean canConvert(Class type) {
return type.equals(Author.class);
}
}
SingleValueConverter 转换成简单字符串
Converter 转换成对象
包别名
xstream.aliasPackage("my.company", "org.thoughtworks");
注解
@XStreamAlias("message") 别名注解
作用目标: 类,字段
@XStreamImplicit 隐式集合
@XStreamImplicit(itemFieldName="part")
作用目标: 集合字段
@XStreamConverter(SingleValueCalendarConverter.class) 注入转换器
作用目标: 对象
@XStreamAsAttribute 转换成属性
作用目标: 字段
@XStreamOmitField 忽略字段
作用目标: 字段
Auto-detect Annotations 自动侦查注解
xstream.autodetectAnnotations(true);
自动侦查注解与XStream.processAnnotations(Class[] cls)的区别在于性能.自动侦查注解将缓存所有类的类型.
对象流
bjectOutputStream out = xstream.createObjectOutputStream(someWriter);
ObjectInputStream in = xstream.createObjectInputStream(someReader);
持久化对象
public void persist(String dir, List objects)
{
PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));
List<?> list = new XmlArrayList(strategy);
list.addAll(objects);
}
JSON
解析器:
Jettison StAX
XStreamFacade.java
- package cn.bisoft.java.test;
- import java.io.File;
- import java.util.List;
- import com.thoughtworks.xstream.XStream;
- import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
- import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
- import com.thoughtworks.xstream.io.xml.DomDriver;
- import com.thoughtworks.xstream.io.xml.XppDriver;
- import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
- import com.thoughtworks.xstream.persistence.PersistenceStrategy;
- import com.thoughtworks.xstream.persistence.XmlArrayList;
- public class XStreamFacade
- {
- private static XStream xstream;
- public static final String JAXP_DOM_XML = "JAXP DOM";
- public static final String XPP3_XML_PARSER = "XPP3";
- public static final String STAX_JSON_PARSER = "Jettison StAX";
- public static final String WRITER_JSON_PARSER = "Only Writer JSON";
- public synchronized static XStream getXStream(String driver)
- {
- if (JAXP_DOM_XML.equals(driver))
- {
- xstream = new XStream(new DomDriver());
- xstream.autodetectAnnotations(true);
- }
- else if (XPP3_XML_PARSER.equals(driver))
- {
- xstream = new XStream(new XppDriver());
- xstream.autodetectAnnotations(true);
- }
- else if (STAX_JSON_PARSER.equals(driver))
- {
- xstream = new XStream(new JettisonMappedXmlDriver());
- xstream.setMode(XStream.NO_REFERENCES);
- }
- else if (WRITER_JSON_PARSER.equals(driver))
- {
- xstream = new XStream(new JsonHierarchicalStreamDriver());
- xstream.setMode(XStream.NO_REFERENCES);
- }
- else
- {
- xstream = new XStream(new DomDriver());
- }
- return xstream;
- }
- @SuppressWarnings("unchecked")
- public void persist(String dir, List objects)
- {
- PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));
- List<?> list = new XmlArrayList(strategy);
- list.addAll(objects);
- }
- }
package cn.bisoft.java.test; import java.io.File; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.persistence.FilePersistenceStrategy; import com.thoughtworks.xstream.persistence.PersistenceStrategy; import com.thoughtworks.xstream.persistence.XmlArrayList; public class XStreamFacade { private static XStream xstream; public static final String JAXP_DOM_XML = "JAXP DOM"; public static final String XPP3_XML_PARSER = "XPP3"; public static final String STAX_JSON_PARSER = "Jettison StAX"; public static final String WRITER_JSON_PARSER = "Only Writer JSON"; public synchronized static XStream getXStream(String driver) { if (JAXP_DOM_XML.equals(driver)) { xstream = new XStream(new DomDriver()); xstream.autodetectAnnotations(true); } else if (XPP3_XML_PARSER.equals(driver)) { xstream = new XStream(new XppDriver()); xstream.autodetectAnnotations(true); } else if (STAX_JSON_PARSER.equals(driver)) { xstream = new XStream(new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); } else if (WRITER_JSON_PARSER.equals(driver)) { xstream = new XStream(new JsonHierarchicalStreamDriver()); xstream.setMode(XStream.NO_REFERENCES); } else { xstream = new XStream(new DomDriver()); } return xstream; } @SuppressWarnings("unchecked") public void persist(String dir, List objects) { PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir)); List<?> list = new XmlArrayList(strategy); list.addAll(objects); } }
------------
扩展:
1.
XBird
2.
XStream.XPATH_RELATIVE_REFERENCES
(Default) Uses relative XPath references to signify duplicate references. This produces XML with the least clutter.
XStream.XPATH_ABSOLUTE_REFERENCES
Uses absolute XPath references to signify duplicate references. This might produce for some situations better readable XML. Note, that XStream will read XML with relative paths as well as with absolute paths independent of the XPATH mode.
XStream.ID_REFERENCES
Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this is easier to work with.
XStream.NO_REFERENCES
This disables object graph support and treats the object structure like a tree. Duplicate references are treated as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than the other two modes.
3.
转换器
示例
XStreamFacade.java
- package cn.bisoft.java.test;
- import java.io.File;
- import java.util.List;
- import com.thoughtworks.xstream.XStream;
- import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
- import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;
- import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
- import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
- import com.thoughtworks.xstream.io.xml.DomDriver;
- import com.thoughtworks.xstream.io.xml.XppDriver;
- import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
- import com.thoughtworks.xstream.persistence.PersistenceStrategy;
- import com.thoughtworks.xstream.persistence.XmlArrayList;
- /**
- * XStreamFacade
- *
- * <pre>
- * 提供对XStream的初始化,降低使用XStream API的复杂性.
- * @link
- * </pre>
- * @author tl
- * @version 1.0, 2011-6-10
- */
- public class XStreamFacade
- {
- public static final String JAXP_DOM_XML = "JAXP DOM";
- public static final String XPP3_XML_PARSER = "XPP3";
- public static final String STAX_JSON_PARSER = "Jettison StAX";
- public static final String WRITER_JSON_PARSER = "Only Writer JSON";
- /**
- * 获取XStream对象.
- *
- * <pre>
- * 根据驱动获取XStream对象,若没有提供驱动,则默认使用JAXP-DOM驱动.
- * </pre>
- * @param driver 驱动名称
- * @param isStaticSupported 是否支持静态变量转换
- * @return XStream
- */
- public synchronized static XStream getXStream(String driver, boolean isStaticSupported)
- {
- ReflectionProvider reflectProvider = null;
- if (isStaticSupported)
- {
- reflectProvider = new EnhancedModeReflectProvider();
- }
- else
- {
- reflectProvider = new Sun14ReflectionProvider();
- }
- if (JAXP_DOM_XML.equals(driver))
- {
- xstream = new XStream(reflectProvider, new DomDriver());
- xstream.autodetectAnnotations(true);
- System.err.println(xstream.getReflectionProvider());
- }
- else if (XPP3_XML_PARSER.equals(driver))
- {
- xstream = new XStream(reflectProvider, new XppDriver());
- xstream.autodetectAnnotations(true);
- }
- else if (STAX_JSON_PARSER.equals(driver))
- {
- xstream = new XStream(reflectProvider, new JettisonMappedXmlDriver());
- xstream.setMode(XStream.NO_REFERENCES);
- }
- else if (WRITER_JSON_PARSER.equals(driver))
- {
- xstream = new XStream(reflectProvider, new JsonHierarchicalStreamDriver());
- xstream.setMode(XStream.NO_REFERENCES);
- }
- else
- {
- xstream = new XStream(reflectProvider, new DomDriver());
- }
- return xstream;
- }
- /**
- * 持久化对象列表.
- *
- * <pre>
- * 持久化对象列表,存储到指定用户主目录下的指定目录
- * </pre>
- * @param dir 目录
- * @param objects 对象列表
- */
- @SuppressWarnings("unchecked")
- public void persist(String dir, List objects)
- {
- PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));
- List<?> list = new XmlArrayList(strategy);
- list.addAll(objects);
- }
- // prinvate fields.
- private static XStream xstream;
- }
package cn.bisoft.java.test; import java.io.File; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.persistence.FilePersistenceStrategy; import com.thoughtworks.xstream.persistence.PersistenceStrategy; import com.thoughtworks.xstream.persistence.XmlArrayList; /** * XStreamFacade * * <pre> * 提供对XStream的初始化,降低使用XStream API的复杂性. * @link * </pre> * @author tl * @version 1.0, 2011-6-10 */ public class XStreamFacade { public static final String JAXP_DOM_XML = "JAXP DOM"; public static final String XPP3_XML_PARSER = "XPP3"; public static final String STAX_JSON_PARSER = "Jettison StAX"; public static final String WRITER_JSON_PARSER = "Only Writer JSON"; /** * 获取XStream对象. * * <pre> * 根据驱动获取XStream对象,若没有提供驱动,则默认使用JAXP-DOM驱动. * </pre> * @param driver 驱动名称 * @param isStaticSupported 是否支持静态变量转换 * @return XStream */ public synchronized static XStream getXStream(String driver, boolean isStaticSupported) { ReflectionProvider reflectProvider = null; if (isStaticSupported) { reflectProvider = new EnhancedModeReflectProvider(); } else { reflectProvider = new Sun14ReflectionProvider(); } if (JAXP_DOM_XML.equals(driver)) { xstream = new XStream(reflectProvider, new DomDriver()); xstream.autodetectAnnotations(true); System.err.println(xstream.getReflectionProvider()); } else if (XPP3_XML_PARSER.equals(driver)) { xstream = new XStream(reflectProvider, new XppDriver()); xstream.autodetectAnnotations(true); } else if (STAX_JSON_PARSER.equals(driver)) { xstream = new XStream(reflectProvider, new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); } else if (WRITER_JSON_PARSER.equals(driver)) { xstream = new XStream(reflectProvider, new JsonHierarchicalStreamDriver()); xstream.setMode(XStream.NO_REFERENCES); } else { xstream = new XStream(reflectProvider, new DomDriver()); } return xstream; } /** * 持久化对象列表. * * <pre> * 持久化对象列表,存储到指定用户主目录下的指定目录 * </pre> * @param dir 目录 * @param objects 对象列表 */ @SuppressWarnings("unchecked") public void persist(String dir, List objects) { PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir)); List<?> list = new XmlArrayList(strategy); list.addAll(objects); } // prinvate fields. private static XStream xstream; }
EnhancedModeReflectProvider.java
- /**
- * <pre>
- * Title: EnhancedModeReflectProvider.java
- * Author: tl
- * Create: 2011-6-10 下午02:50:18
- * Copyright: Copyright (c) 2011
- * Company: Shenzhen *****
- * <pre>
- */
- package cn.bisoft.java.test;
- import java.lang.reflect.Field;
- import java.lang.reflect.Modifier;
- import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;
- /**
- * <pre>
- * 支持静态字段转换,但有缺陷,字段不能映射成属性.
- * </pre>
- * @author tl
- * @version 1.0, 2011-6-10
- */
- public class EnhancedModeReflectProvider extends Sun14ReflectionProvider
- {
- @Override
- protected boolean fieldModifiersSupported(Field field)
- {
- return !(Modifier.isTransient(field.getModifiers()));
- }
- }
/** * <pre> * Title: EnhancedModeReflectProvider.java * Author: tl * Create: 2011-6-10 下午02:50:18 * Copyright: Copyright (c) 2011 * Company: Shenzhen ***** * <pre> */ package cn.bisoft.java.test; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider; /** * <pre> * 支持静态字段转换,但有缺陷,字段不能映射成属性. * </pre> * @author tl * @version 1.0, 2011-6-10 */ public class EnhancedModeReflectProvider extends Sun14ReflectionProvider { @Override protected boolean fieldModifiersSupported(Field field) { return !(Modifier.isTransient(field.getModifiers())); } }
ExampleMessageBody.java
- package cn.bisoft.java.test;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import com.thoughtworks.xstream.annotations.XStreamAlias;
- import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
- import com.thoughtworks.xstream.annotations.XStreamInclude;
- import com.thoughtworks.xstream.annotations.XStreamOmitField;
- @SuppressWarnings("unused")
- @XStreamAlias("body")
- public class ExampleMessageBody
- {
- @XStreamAsAttribute
- private static final String type = "example";
- private String id = "message id";
- private Date timestamp;
- /** 当userList节点必须存在是, 需要初始化. 值为空的字段是不会输出到XML的. */
- @XStreamAlias("users")
- private List<User> userList = new ArrayList<User>();
- @XStreamAlias("user")
- public static class User
- {
- @XStreamAsAttribute
- private String id;
- @XStreamAsAttribute
- private Date birth;
- @XStreamOmitField
- private String password;
- public String getId()
- {
- return id;
- }
- public void setId(String id)
- {
- this.id = id;
- }
- public Date getBirth()
- {
- return birth;
- }
- public void setBirth(Date birth)
- {
- this.birth = birth;
- }
- public String getPassword()
- {
- return password;
- }
- public void setPassword(String password)
- {
- this.password = password;
- }
- }
- public String getId()
- {
- return id;
- }
- public void setId(String id)
- {
- this.id = id;
- }
- public Date getTimestamp()
- {
- return timestamp;
- }
- public void setTimestamp(Date timestamp)
- {
- this.timestamp = timestamp;
- }
- public List<User> getUserList()
- {
- return userList;
- }
- public void setUserList(List<User> userList)
- {
- this.userList = userList;
- }
- }
package cn.bisoft.java.test; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamInclude; import com.thoughtworks.xstream.annotations.XStreamOmitField; @SuppressWarnings("unused") @XStreamAlias("body") public class ExampleMessageBody { @XStreamAsAttribute private static final String type = "example"; private String id = "message id"; private Date timestamp; /** 当userList节点必须存在是, 需要初始化. 值为空的字段是不会输出到XML的. */ @XStreamAlias("users") private List<User> userList = new ArrayList<User>(); @XStreamAlias("user") public static class User { @XStreamAsAttribute private String id; @XStreamAsAttribute private Date birth; @XStreamOmitField private String password; public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } }
TestXStream.java
- package cn.bisoft.java.test;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import com.thoughtworks.xstream.XStream;
- public class TestXStream
- {
- public static void main(String[] args)
- {
- XStream xstream = XStreamFacade.getXStream(XStreamFacade.JAXP_DOM_XML, true);
- ExampleMessageBody body = new ExampleMessageBody();
- body.setId("0");
- body.setTimestamp(new Date());
- List<ExampleMessageBody.User> userList = new ArrayList<ExampleMessageBody.User>();
- ExampleMessageBody.User user = new ExampleMessageBody.User();
- user.setBirth(new Date());
- user.setId("tl");
- user.setPassword("123456");
- userList.add(user);
- body.setUserList(userList);
- xstream.useAttributeFor("type", ExampleMessageBody.class);
- String xml = xstream.toXML(body);
- System.out.println(xml);
- }
- }
package cn.bisoft.java.test; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.thoughtworks.xstream.XStream; public class TestXStream { public static void main(String[] args) { XStream xstream = XStreamFacade.getXStream(XStreamFacade.JAXP_DOM_XML, true); ExampleMessageBody body = new ExampleMessageBody(); body.setId("0"); body.setTimestamp(new Date()); List<ExampleMessageBody.User> userList = new ArrayList<ExampleMessageBody.User>(); ExampleMessageBody.User user = new ExampleMessageBody.User(); user.setBirth(new Date()); user.setId("tl"); user.setPassword("123456"); userList.add(user); body.setUserList(userList); xstream.useAttributeFor("type", ExampleMessageBody.class); String xml = xstream.toXML(body); System.out.println(xml); } }
说明:
1. 静态字段其实没有必要序列化.
2. 集合类型通常需要进行初始化.
发表评论
-
xstream xml
2012-05-20 14:41 753http://wenku.baidu.com/view/2d0 ... -
[Java]一则自定义的XStream转换器,主要用于POJO XML反序列化为Map/List
2012-05-20 14:38 6076使用轻量级的XStream可以很方便的将对象序列化为XML ... -
dom4j 对xml接线
2012-05-20 13:56 946Dom4j功能解析 SAXReader reade ... -
object to xml
2012-05-17 15:25 1298http://www.cnblogs.com/java-pan ... -
java xml2Object
2012-05-17 07:58 1476JAXB的话是java1.5之后出现的,对于java对象和xm ... -
xml解析的4种做法,及效率测试
2009-08-21 17:00 1663在平时工作中,难 ...
相关推荐
XStream是一个强大的库,它使得XML与Java对象之间的转换变得简单。在这个主题中,我们将深入探讨如何使用XStream进行XML与Java对象的互换,并了解其工作原理。 首先,XStream是一个开源库,由Johannes Leutenegger...
本篇文章将深入探讨xStream如何实现Java对象与XML和JSON的相互转换,并提供详细的代码示例。 ### 1. xStream的安装与引入 首先,你需要在项目中添加xStream的依赖。如果你使用的是Maven,可以在pom.xml文件中添加...
在这个场景中,我们将探讨如何使用XStream将XML文档转换成Java对象,进而转化为JSON对象。 首先,我们需要引入XStream库。XStream的核心功能是能够将Java对象和XML之间的映射自动化,极大地简化了序列化和反序列化...
XStream是一款强大的库,它使得Java对象与XML之间的转换变得简单易行。本篇文章将深入探讨如何利用XStream进行Java对象到XML的转换,并将其存储到SD卡上。 首先,XStream的核心功能在于它可以将Java对象直接转换为...
标题中的“XStream实现Object与XML转换解决方案”指的是一个Java库——XStream,它提供了一种简单的方法来序列化和反序列化Java对象到XML,反之亦然。这个库广泛用于将程序数据保存到XML文件或者从XML数据恢复对象,...
MyObject myObject = (MyObject) xstream.fromXML(xml); ``` 这段代码会将之前生成的 XML 字符串 `xml` 反序列化回 `MyObject` 类型的实例。 **XStream 特性** 1. **类型安全**:XStream 使用了类型安全的反射...
在Java开发中,XStream 提供了一种简洁的方式来将复杂的对象结构转换为XML格式,反之亦然。 ### XStream组件基础 XStream 的核心功能是通过`toXML()`和`fromXML()`两个方法来实现对象和XML之间的转换。首先,你...
在`xmlAnalysis`文件夹中,可能包含了一个简单的Java程序,演示了如何使用DOM、SAX、StAX和XStream解析XML文件,并展示了XStream如何在JavaBean与XML之间进行转换。你可以运行这些代码,观察输出结果,以加深理解。...
这两个工具都提供了简单易用的API,帮助我们实现XML到对象(Object-to-XML)和对象到XML(XML-to-Object)的转换。 **XStream** XStream是Joe Walnes创建的一个开源库,它允许开发者以一种直观、简洁的方式在Java...
本篇文章将深入探讨如何使用XStream实现XML与Java对象的转换,并着重讲解转换器的概念。 XStream的核心功能在于它可以自动将Java对象转换成XML表示,反之亦然。这个过程是通过反射和元数据驱动的,使得开发人员无需...
总的来说,XStream是一个功能丰富的库,它使得Java对象与XML之间的转换变得简单易行。通过理解和掌握XStream的用法,开发者可以更高效地处理数据序列化需求,无论是在存储、传输还是解析XML文档的场景下。
XStream简化了对象和XML之间的转换,而XPP3则提供了一个快速且低内存占用的XML解析器。如果你需要在Java项目中处理XML,这两个库是值得考虑的。在使用前,确保正确地导入它们,并根据项目需求配置好相应的安全设置。
`xstream-1.3.1.jar`是XStream的一个版本,支持将任何复杂的Java对象结构转换为同等的XML表示,同时也支持反向转换。在微信开发中,如果需要将Java对象转换为XML进行传输,或者从微信返回的XML数据中恢复对象状态,...
【XML,Object,Json转换与Xstream的使用详解】 XML,Object,Json转换在软件开发中扮演着重要的角色,尤其是在数据交换和存储方面。Xstream是一个强大的Java库,它简化了对象与XML之间的序列化和反序列化过程。...
在本文中,我们将深入探讨XStream的核心功能,以及如何利用它来实现XML与Java对象之间的转换。 1. **XStream简介** XStream由Johannes Brodbeck开发,它的设计目标是提供一个易于使用且高效的XML序列化框架。它...
标题 "xStream完美转换XML、JSON" 指的是使用xStream库在Java中进行XML与JSON数据格式之间的转换。xStream是一个强大的库,它提供了一种简单的方式来序列化和反序列化Java对象到XML,反之亦然。在这个场景中,它同样...
**xStream-1.31 jar包:XML与JSON数据转换的神器** 在Java开发中,数据序列化和反序列化是一项重要的任务,它涉及到对象与字符串格式(如XML或JSON)之间的转换。xStream库就是一个这样的工具,它提供了一个简单...
XStream是一款强大的Java库,主要用于实现Java对象与XML文档之间的相互转换。本文将详细介绍XStream的基本用法、配置选项以及如何利用它来进行对象到XML的序列化和反序列化操作。 #### 一、XStream简介 XStream是...
转换器是XStream的核心机制之一,它负责将Java对象转化为XML元素,以及将XML元素解析回相应的Java对象。`@XStreamConverter`注解则用于指定一个自定义的转换器类,帮助我们处理特定类型的对象,比如Date。 在处理...