Xsteam Intro
XStream是thoughtworks开发的开源产品,采用的是xpp来进行xml和对象之间的转换。它不需要schema或其他的mapping文件就可以进行java对象和xml文件之间的转换,API调用起来非常方便,并且扩展功能强大。Offical site: http://xstream.codehaus.org/index.html
官方介绍:XStream is a simple library to serialize objects to XML and back again.
Feature list:
Ø Ease of use. A high level facade is supplied that simplifies common use cases.
Ø No mappings required. Most objects can be serialized without need for specifying mappings.
Ø Performance. Speed and low memory footprint are a crucial part of the design, making it suitable for large object graphs or systems with high message throughput.
Ø Clean XML. No information is duplicated that can be obtained via reflection. This results in XML that is easier to read for humans and more compact than native Java serialization.
Ø Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
Ø Full object graph support. Duplicate references encountered in the object-model will be maintained. Supports circular references.
Ø Integrates with other XML APIs. By implementing an interface, XStream can serialize directly to/from any tree structure (not just XML).
Ø Customizable conversion strategies. Strategies can be registered allowing customization of how particular types are represented as XML.
Ø Error messages. When an exception occurs due to malformed XML, detailed diagnostics are provided to help isolate and fix the problem.
Ø Alternative output format. The modular design allows other output formats. XStream ships currently with JSON support and morphing.
Note: 在配合JDK1.4或者1.3版本使用时,由于Xstream会任意根据Class实例化对象,所以会存在一些于老JVM安全框架上的冲突。
Demo to use:
首先只要编写一个POJO对象,而且这个对象甚至不需要getter/setter方法。同事对象的访问描述符是public还是private, Xstream并不关心。
接下来,构造一个XStream实例(此类利用了Façade设计模式,所有的方法都是for common use),传递字定义的POJO class对象给XStream,之后使用该实例的toXML和fromXML就可以自由转换Java Object和XML String了。