/Prototipo/Servlet/lib/xstream-distribution-1.4.1-bin/xstream-1.4.1/docs/faq.html

http://prototipomemoria.googlecode.com/ · HTML · 750 lines · 513 code · 146 blank · 91 comment · 0 complexity · 4dd84fd52ba05fbfeb7c3d479e4551e5 MD5 · raw file

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <!--
  4. Copyright (C) 2005, 2006 Joe Walnes.
  5. Copyright (C) 2006, 2007, 2008 XStream committers.
  6. All rights reserved.
  7. The software in this package is published under the terms of the BSD
  8. style license a copy of which has been included with this distribution in
  9. the LICENSE.txt file.
  10. Created on 29. January 2005 by Joe Walnes
  11. -->
  12. <head>
  13. <title>XStream - Frequently Asked Questions</title>
  14. <link rel="stylesheet" type="text/css" href="style.css"/>
  15. <!-- Google analytics -->
  16. <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
  17. </script>
  18. <script type="text/javascript">
  19. _uacct = "UA-110973-2";
  20. urchinTracker();
  21. </script>
  22. </head>
  23. <body>
  24. <div id="banner">
  25. <a href="index.html"><img id="logo" src="logo.gif" alt="XStream"/></a>
  26. </div>
  27. <div id="center" class="Content2Column"> <!-- Content3Column for index -->
  28. <div id="content">
  29. <h1 class="FirstChild">Frequently Asked Questions</h1>
  30. <ol>
  31. <li><a href="#Compatibility">Compatibility</a></li>
  32. <li><a href="#Serialization">Serialization</a></li>
  33. <li><a href="#XML">XML specifics</a></li>
  34. <li><a href="#JSON">JSON specifics</a></li>
  35. <li><a href="#Other_Products">Comparison to other products</a></li>
  36. <li><a href="#Scalability">Scalability</a></li>
  37. <li><a href="#Uses">Uses of XStream</a></li>
  38. </ol>
  39. <!-- ****************************************************** -->
  40. <h1 id="Compatibility">Compatibility</h1>
  41. <!-- ...................................................... -->
  42. <h2 id="Compatibility_JDK">Which JDK is required to use XStream?</h2>
  43. <p>1.4 or later.</p>
  44. <!-- ...................................................... -->
  45. <h2 id="Compatibility_JVMs">Does XStream behave differently across different JVMs?</h2>
  46. <p>XStream has two modes of operation: <b>Pure Java</b> and <b>Enhanced</b>. In pure Java mode,
  47. XStream behaves in the same way across different JVMs, however its features are limited to what
  48. reflection allows, meaning it cannot serialize certain classes or fields. In <b>enhanced</b> mode,
  49. XStream does not have these limitations, however this mode of operation is not available to all JVMs.</p>
  50. <!-- ...................................................... -->
  51. <h2 id="Compatibility_enhanced_mode_jvm">Which JVMs allow XStream to operate in enhanced mode?</h2>
  52. <p>Currently on the Sun, Apple, HP, IBM and Blackdown 1.4 JVMs and onwards.
  53. Also for Hitachi, SAP and Diablo from 1.5 and onwards.
  54. Support for BEA JRockit starting with R25.1.0.
  55. OpenJDK 6 is also supported.
  56. For all other JVMs, XStream should be used in pure Java mode.</p>
  57. <!-- ...................................................... -->
  58. <h2 id="Compatibility_enhanced_mode_advantage">What are the advantages of using enhanced mode over pure Java mode?</h2>
  59. <table summary="Comparison of pure Java and enhanced mode">
  60. <tr><th>Feature</th><th>Pure Java</th><th>Enhanced Mode</th></tr>
  61. <tr><td>Public classes</td><td>Yes</td><td>Yes</td></tr>
  62. <tr><td>Non public classes</td><td>No</td><td>Yes</td></tr>
  63. <tr><td>Static inner classes</td><td>Yes</td><td>Yes</td></tr>
  64. <tr><td>Non-static inner classes</td><td>No</td><td>Yes</td></tr>
  65. <tr><td>Anonymous inner classes</td><td>No</td><td>Yes</td></tr>
  66. <tr><td>With default constructor</td><td>Yes</td><td>Yes</td></tr>
  67. <tr><td>Without default constructor</td><td>No</td><td>Yes</td></tr>
  68. <tr><td>Private fields</td><td>Yes</td><td>Yes</td></tr>
  69. <tr><td>Final fields</td><td>Yes &gt;= JDK 1.5</td><td>Yes</td></tr>
  70. </table>
  71. <!-- ...................................................... -->
  72. <h2 id="Compatibility_XPP">Why is my application not able to create a XmlPullParser with the XppDriver since XStream 1.4?</h2>
  73. <p>The <a href="http://www.xmlpull.org/">XML Pull Parser API</a> defines an own mechanism to load the factory for
  74. the available XPP implementation. XStream's XppDriver never used this lookup mechanism automatically before version
  75. 1.4, now it will. Therefore you will have to add a <a href="download.html#optional-deps">dependency to xmlpull</a>
  76. if the XPP implementation does not deliver the classes on its own. This dependency is necessary for Xpp3 in
  77. contrast to kXML2 that contains the classes. Use the Xpp3Driver or the KXml2Driver if you want to select one of the
  78. directly supported XPP implementation on your own without using the XPP factory. Note, that the minimal version of
  79. kXML2 does not support the XPP factory, but can be used by the KXml2Driver.</p>
  80. <!-- ...................................................... -->
  81. <h2 id="Compatibility_Android">Can I use XStream in an Android application?</h2>
  82. <p>XStream does work in Android 1.0, but is reported to have limited capabilities. Since XStream 1.4 Android is
  83. treated at least as JD 5 platform, but it e.g. does not include the java.beans package. Therefore you cannot use
  84. the JavaBeanConverter. Note, that Android provides an XML Pull Parser, therefore XStream can work without
  85. additional dependencies.</p>
  86. <!-- ...................................................... -->
  87. <h2 id="Compatibility_Harmony">Why does XStream fail on Harmony?</h2>
  88. <p>Since JDK 5 it is possible according the Java specification to write into final fields using reflection. This is not yet
  89. supported by Harmony and therefore the PureJavaReflectionProvider fails. We have also already investigated into
  90. enhanced mode in Harmony, but the Harmony JVM currently crashes running the unit tests. It is simply not yet ready.</p>
  91. <!-- ...................................................... -->
  92. <h2 id="Compatibility_unsupported_JVM">Are there plans to provide enhanced mode support to other JVMs?</h2>
  93. <p>Yes. <a href="list-user.html">Let us know</a> which JVM you would like supported.</p>
  94. <!-- ...................................................... -->
  95. <h2 id="Compatibility_no_enhanced_mode">When should I use XStream not in enhanced mode?</h2>
  96. <p>Running XStream in a secured environment can prevent XStream from running in enhanced mode. This is
  97. especially true when running XStream in an applet. You may also try to use the JavaBeanConverter as alternative to
  98. the ReflectionConverter running in enhanced or pure Java mode.</p>
  99. <!-- ...................................................... -->
  100. <h2 id="Compatibility_SecurityManager">Which permissions does XStream need when running with an active SecurityManager?</h2>
  101. <p>This depends on the mode XStream is running in. Refer to the
  102. <a href="http://svn.xstream.codehaus.org/browse/xstream/trunk/xstream/src/test/com/thoughtworks/acceptance/SecurityManagerTest.java">SecurityManagerTest</a>
  103. for details.</p>
  104. <!-- ...................................................... -->
  105. <h2 id="Compatibility_XStream11">Why does XStream 1.2 no longer read XML generated with XStream 1.1.x?</h2>
  106. <p>The architecture in XStream has slightly changed. Starting with XStream 1.2 the
  107. <a href="javadoc/com/thoughtworks/xstream/io/HierarchicalStreamDriver.html">HierarchicalStreamDriver</a>
  108. implementation is responsible to ensure that XML tags and attributes are valid names in XML, in XStream 1.1.x
  109. this responsibility was part of the ClassMapper implementations. Under some rare circumstances this will result in
  110. an unreadable XML due to the different processing order in the workflow of such problematic tag names.</p>
  111. <p>You can run XStream in 1.1 compatibility mode though:</p>
  112. <div class="Source Java"><pre>XStream xstream = new XStream(new XppDriver(new XStream11XmlFriendlyReplacer())) {
  113. protected boolean useXStream11XmlFriendlyMapper() {
  114. return true;
  115. }
  116. };</pre></div>
  117. <!-- ...................................................... -->
  118. <h2 id="Compatibility_ConverterAnnotations">XStream 1.3 ignores suddenly annotated converters (@XStreamConverter and @XStreamConverters)?</h2>
  119. <p>XStream treats now all annotations the same and therefore it no longer auto-detects any annotation by
  120. default. You can configure XStream to run in auto-detection mode, but be aware if the
  121. <a href="annotations-tutorial.html#AutoDetect">implications</a>. As alternative you might register the
  122. deprecated AnnotationReflectionConverter, that was used for XStream pre 1.3.x, but as drawback the functionality
  123. to register a local converter with XStream.registerLocalConverter will no longer work.</p>
  124. <!-- ...................................................... -->
  125. <h2 id="Compatibility_element_sequence">XStream 1.3 suddenly has a different field order?</h2>
  126. <p>Yes. This was announced with the last 1.2.x release and was done to support the type inheritance of XML schemas. However, XStream is delivered with the
  127. <a href="javadoc/com/thoughtworks/xstream/io/HierarchicalStreamDriver.html">XStream12FieldKeySorter</a> that can be used to
  128. <a href="#Serialization_sort_fields">sort the fields</a> according XStream 1.2.2.</p>
  129. <!-- ****************************************************** -->
  130. <h1 id="Serialization">Serialization</h1>
  131. <!-- ...................................................... -->
  132. <h2 id="Serialization_types">Which class types can be serialized by XStream?</h2>
  133. <p>In contrast to the JDK XStream is not tied to a marker interface to serialize a class. XStream ships with some specialized <a href="converters.html">converters</a>,
  134. but will use reflection by default for &quot;unknown&quot; classes to examine, read and write the class' data. Therefore XStream can handle quite any class, especially
  135. the ones referred as POJO (Plain Old Java Object).</p>
  136. <p>However, some types of classes exist with typical characteristics, that cannot be handled - at least not out of the box:</p>
  137. <ol>
  138. <li>Objects that are based on threads or thread local data: Thread, Timer, ThreadLocal and so on. These classes keep different data for different threads and there's
  139. no possibility to recreate a thread in a generic way nor recreating thread specific data. There might be special use cases, but this will always involve a custom converter
  140. where threads can be recreated in a specific way tied to that use case.</li>
  141. <li>Class types that are based on generated classes. Such types have often names that are unique to the current process and will have no meaning
  142. in a different process. A custom converter might help to write the appropriate data into the serializing stream to be able to recreate a equivalent class at deserialization
  143. time.</li>
  144. <li>Types that keep and use system resources like file handles, sockets, pipes and so on. ClassLoader, FileInputStream, FileOutputStream, Socket and so on. To
  145. deserialize such a class the converter must be able to claim the appropriate resource from the system again. With the help of a custom converter this might be
  146. possible, but with the reflection converter the deserialized class might refer a system resource that is no longer valid or belongs to somebody else. Behavior is
  147. undefined then.</li>
  148. <li>A very special case of such allocated system resources are those classes that keep handles to system memory directly, because they are partly implemented native.
  149. It is known to be true for the Linux version of Sun's JDK that the BufferedImage references some system specific types of the JDK that themselves have member fields
  150. with such memory handles. While it is possible at first sight to serialize and deserialize a BufferedImage, the reflection converter will also duplicate the memory handle.
  151. As a result the JVM might crash easily because of freeing unallocated memory or freeing the same memory twice. It might be possible to create a custom converter,
  152. but the data structure is really complex in this area and nobody has been investigating so far to such an extent. However, <strong>do not use the reflection converter
  153. for these types! You have been warned!</strong></li>
  154. <li>Inner class types of the JDK can often vary in implementation details between JDK versions and vendors and are therefore only compatible for the same JDK. This
  155. includes collection types returned by the methods of the Collections class that wrap another one (like unmodifiableList) or the collections that are returned by the
  156. different Map implementations for the keySet(), entrySet() and values() methods.</li>
  157. </ol>
  158. <!-- ...................................................... -->
  159. <h2 id="Serialization_omit_field">How do I specify that a field should not be serialized?</h2>
  160. <p>Make it <code>transient</code>, specify it with <code>XStream.omitField()</code> or
  161. annotate it with @XStreamOmitField</p>
  162. <!-- ...................................................... -->
  163. <h2 id="Serialization_initialize_transient">How do I initialize a transient field at deserialization?</h2>
  164. <p>XStream uses the same mechanism as the JDK serialization. Example:</p>
  165. <div class="Source Java"><pre>class ThreadAwareComponent {
  166. private transient ThreadLocal component;
  167. // ...
  168. private Object readResolve() {
  169. component = new ThreadLocal();
  170. return this;
  171. }
  172. }</pre></div>
  173. <!-- ...................................................... -->
  174. <h2 id="Serialization_no_ctor_running">XStream is not calling the default constructor during deserialization.</h2>
  175. <p>This is, in fact, the same case as above. XStream uses the same mechanism as the JDK serialization. When using
  176. the enhanced mode with the optimized reflection API, it does not invoke the default constructor. The solution is to
  177. implement the readResolve method as above:</p>
  178. <div class="Source Java"><pre>class MyExecutor {
  179. private Object readResolve() {
  180. // do what you need to do here
  181. System.out.println("After instantiating MyExecutor");
  182. // at the end returns itself
  183. return this;
  184. }
  185. }</pre></div>
  186. <!-- ...................................................... -->
  187. <h2 id="Serialization_collections">What do serialized collections look like?</h2>
  188. <p>See example for the <a href="converters.html#java.util">CollectionConverter</a>.</p>
  189. <p>Note, that it is possible to configure XStream to omit the container element <i>toys</i> using implicit collections.</p>
  190. <!-- ...................................................... -->
  191. <h2 id="Serialization_Serializable">Do my classes have to implement Serializable if XStream is to serialize them?</h2>
  192. <p>No.</p>
  193. <!-- ...................................................... -->
  194. <h2 id="Serialization_proxies">Can dynamic proxies be serialized?</h2>
  195. <p>Yes.</p>
  196. <!-- ...................................................... -->
  197. <h2 id="Serialization_CGLIB">Can CGLIB proxies be serialized?</h2>
  198. <p>Only limitedly. A proxy generated with the CGLIB Enhancer is supported, if the proxy uses either a factory or
  199. only one callback. Then it is possible to recreate the proxy instance at unmarshalling time. Starting with XStream 1.3.1
  200. CGLIB support is no longer automatically installed because of possible classloader problems and side-effects,
  201. because of incompatible ASM versions. You can enable CGLIB support with:</p>
  202. <div class="Source Java"><pre>XStream xstream = new XStream() {
  203. protected MapperWrapper wrapMapper(MapperWrapper next) {
  204. return new CGLIBMapper(next);
  205. }
  206. };
  207. xstream.registerConverter(new CGLIBEnhancedConverter(xstream.getMapper(), xstream.getReflectionProvider()));
  208. </pre></div>
  209. <!-- ...................................................... -->
  210. <h2 id="Serialization_CGLIB_ExceptionInInitializerError">CGLIBEnhancedConverter fails at initialization with ExceptionInInitializerError</h2>
  211. <p>This is not a problem of XStream. You have incompatible ASM versions in your classpath. CGLIB 2.1.x and below is based on
  212. ASM 1.5.x which is incompatible to newer versions that are used by common packages like Hibernate, Groovy or Guice. Check
  213. your dependencies and ensure that you are using either using cglib-nodep-2.x.jar instead of cglib-2.x.jar or update to
  214. cglib-2.2.x that depends on ASM 3.1. However, the <em>nodep</em> version contains a copy of the ASM classes with private
  215. packages and will therefore not raise class incompatibilities at all.</p>
  216. <!-- ...................................................... -->
  217. <h2 id="Serialization_CGLIB_2.0.1">Serialization fails with NoSuchMethodError: net.sf.cglib.proxy.Enhancer.isEnhanced(Ljava/lang/Class;)Z</h2>
  218. <p>XStream uses this method to detect a CGLIB-enhanced proxy. Unfortunately the method is not available in the
  219. cglib-2.0 version. Since this version is many years old and the method is available starting with cglib-2.0.1, please
  220. consider an upgrade of the dependency, it works usually smoothly.</p>
  221. <!-- ...................................................... -->
  222. <h2 id="Serialization_Hibernate">How do I use XStream's Hibernate package to serialize my objects?</h2>
  223. <p>Support of Hibernate enhanced collections and proxied types. To drop the internals of Hibernate when marshalling
  224. such objects to XStream, all converters and the mapper has to be registered for the XStream instance:</p>
  225. <div class="Source Java"><pre>final XStream xstream = new XStream() {
  226. protected MapperWrapper wrapMapper(final MapperWrapper next) {
  227. return new HibernateMapper(next);
  228. }
  229. };
  230. xstream.registerConverter(new HibernateProxyConverter());
  231. xstream.registerConverter(new HibernatePersistentCollectionConverter(xstream.getMapper()));
  232. xstream.registerConverter(new HibernatePersistentMapConverter(xstream.getMapper()));
  233. xstream.registerConverter(new HibernatePersistentSortedMapConverter(xstream.getMapper()));
  234. xstream.registerConverter(new HibernatePersistentSortedSetConverter(xstream.getMapper()));
  235. </pre></div>
  236. <!-- ...................................................... -->
  237. <h2 id="Serialization_system_attributes">My attributes are interpreted by XStream itself and cause unexpected behavior</h2>
  238. <p>XStream's generic converters and the marshalling strategies use a number of attributes on their own. Especially the attributes named
  239. <em>id</em>, <em>class</em> and <em>reference</em> are likely to cause such collisions. Main reason is XStream's history, because
  240. originally user defined attributes were not supported and all attribute were system generated. Starting with XStream 1.3.1 you can redefine
  241. those attributes to allow the names to be used for your own ones. The following snippet defines XStream to use different system attributes
  242. for <em>id</em> and <em>class</em> while the field <em>id</em> of YourClass is written into the attribute <em>class</em>:</p>
  243. <div class="Source Java"><pre>XStream xstream = new XStream() {
  244. xstream.useAttributeFor(YourClass.class, "id");
  245. xstream.aliasAttribute("class", "id");
  246. xstream.aliasSystemAttribute("type", "class");
  247. xstream.aliasSystemAttribute("refid", "id");
  248. </pre></div>
  249. <!-- ...................................................... -->
  250. <h2 id="Serialization_sort_fields">Can I select the field order in which XStream serializes objects?</h2>
  251. <p>Yes. XStream's ReflectionConverter uses the defined field order by default. You can override it by using an specific FieldKeySorter:</p>
  252. <div class="Source Java"><pre>SortableFieldKeySorter sorter = new SortableFieldKeySorter();
  253. sorter.registerFieldOrder(MyType.class, new String[] { "firstToSerialize", "secondToSerialize", "thirdToSerialize" });
  254. xstream = new XStream(new Sun14ReflectionProvider(new FieldDictionary(sorter)));
  255. </pre></div>
  256. <!-- ...................................................... -->
  257. <h2 id="Serialization_newer_class_versions">How does XStream deal with newer versions of classes?</h2>
  258. <ul>
  259. <li>If a new field is added to the class, deserializing an old version will leave the field uninitialized.</li>
  260. <li>If a field is removed from the class, deserializing an old version that contains the field will cause an exception.
  261. Leaving the field in place but declaring it as transient will avoid the exception, but XStream will not try to deserialize it.</li>
  262. <li>If a class is renamed, aliases can be used to create an abstraction between the name used in XML and the real class name.</li>
  263. <li>If a field is renamed, this should be treated as adding a field and removing a field.</li>
  264. </ul>
  265. <p>For more advanced class migrations, you may</p>
  266. <ul>
  267. <li>have to do custom pre-processing of the XML before sending it to XStream (for example, with XSLT or DOM manipulations)</li>
  268. <li>declare new fields as transient</li>
  269. <li>implement your own converter, that can handle the situation</li>
  270. <li>add a readResolve() method to your class, that initializes the object accordingly</li>
  271. <li>implement a custom mapper to ignore unknown fields automatically
  272. (see acceptance test CustomMapperTest.testCanBeUsedToOmitUnexpectedElements())</li>
  273. </ul>
  274. <p>Future versions of XStream will include features to make these type of migrations easier.</p>
  275. <!-- ...................................................... -->
  276. <h2 id="Serialization_classloader">How does XStream cope with isolated class loaders?</h2>
  277. <p>Serializing an object graph is never a problem, even if the classes of those objects have been loaded by
  278. a different class loader. The situation changes completely at deserialization time. In this case you must set the
  279. class loader to use with:</p>
  280. <div class="Source Java"><pre>xstream.setClassLoader(yourClassLoader);</pre></div>
  281. <p>Although XStream caches a lot of type related information to gain speed, it keeps those information in
  282. tables with weak references that should be cleaned by the garbage collector when the class loader is freed.</p>
  283. <p>Note, that this call should be made quite immediately after creating the XStream and before any other
  284. configuration is done. Otherwise configuration based on special types might refer classes loaded with the wrong
  285. classloader.</p>
  286. <!-- ****************************************************** -->
  287. <h1 id="XML">XML specifics</h1>
  288. <!-- ...................................................... -->
  289. <h2 id="XML_respect_encoding">Why does XStream not respect the encoding in the XML declaration?</h2>
  290. <p>XStream architecture is based on IO Readers and Writers, while the XML declaration is the responsibility of XML
  291. parsers. All <a href="javadoc/com/thoughtworks/xstream/io/HierarchicalStreamDriver.html">HierarchicalStreamDriver</a>
  292. implementations respect the encoding since version 1.3, but only if you provide an
  293. <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStream.html">InputStream</a>. If XStream consumes a
  294. <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.html">Reader</a> you have to initialize the reader with
  295. the appropriate encoding yourself, since it is now the reader's task to perform the encoding and no XML parser can
  296. change the encoding of a Reader and any encoding definition in the XML header will be ignored.</p>
  297. <!-- ...................................................... -->
  298. <h2 id="XML_write_XML_declaration">Why does XStream not write an XML declaration?</h2>
  299. <p>XStream is designed to write XML snippets, so you can embed its output into an existing stream or string.
  300. You can write the XML declaration yourself into the Writer before using it to call XStream.toXML(writer).</p>
  301. <!-- ...................................................... -->
  302. <h2 id="XML_write_UTF8">Why does XStream not write XML in UTF-8?</h2>
  303. <p>XStream does no character encoding by itself, it relies on the configuration of the underlying XML writer.
  304. By default it uses its own PrettyPrintWriter which writes into the default encoding of the current locale. To write
  305. UTF-8 you have to provide a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.html">Writer</a>
  306. with the appropriate encoding yourself.</p>
  307. <!-- ...................................................... -->
  308. <h2 id="XML_double_underscores">Why do field names suddenly have double underscores in the generated XML?</h2>
  309. <p>XStream maps Java class names and field names to XML tags or attributes. Unfortunately this mapping cannot
  310. be 1:1, since some characters used for <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.8">
  311. identifiers in Java</a> are invalid in <a href="http://www.w3.org/TR/REC-xml/#dt-name">XML names</a>. Therefore
  312. XStream uses an <a href="javadoc/com/thoughtworks/xstream/io/xml/XmlFriendlyNameCoder.html">XmlFriendlyNameCoder</a>
  313. to replace these characters with a replacement. By default this
  314. <a href="javadoc/com/thoughtworks/xstream/io/naming/NameCoder.html">NameCoder</a> uses an underscore as escape
  315. character and has therefore to escape the underscore itself also. You may provide a different configured instance
  316. of the XmlFriendlyNameCoder or a complete different implementation like the
  317. <a href="javadoc/com/thoughtworks/xstream/io/xml/XmlFriendlyNameCoder.html">NoNameCoder</a> to prevent name coding
  318. at all. However it is your responsibility then to ensure, that the resulting names are valid for XML.</p>
  319. <!-- ...................................................... -->
  320. <h2 id="XML_unmarshalling_fails">XStream fails to unmarshal my given XML and I do not know why?</h2>
  321. <p>By default XStream is written for persistence i.e. it will read the XML it can write. If you have to transform
  322. a given XML into an object graph, you should go the other way round. Use XStream to transfer your objects into XML.
  323. If the written XML matches your schema, XStream is also able to read it. This way is much easier, since you can
  324. spot the differences in the XML much more easy than to interpret the exceptions XStream will throw if it cannot
  325. match the XML into your objects.</p>
  326. <!-- ...................................................... -->
  327. <h2 id="XML_null_char">My parser claims the &amp;#x0; character to be invalid, but it was written with XStream!</h2>
  328. <p>Your parser is basically right! A character of value 0 is not valid as part of XML according the XML specification (see
  329. version <a href="http://www.w3.org/TR/2006/REC-xml-20060816/#charsets">1.0</a> or
  330. <a href="http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets">1.1</a>), neither directly nor as character
  331. entity nor within CDATA. But not every parser respects this part of the specification (e.g. Xpp3 will ignore it and read
  332. character entities). If you expect such characters in your strings and you do not use the Xpp3 parser, you should consider
  333. to use a converter that writes the string as byte array in Base64 code. As alternative you may force the
  334. <a href="javadoc/com/thoughtworks/xstream/io/xml/PrettyPrintWriter.html">PrettyPrintWriter</a> or derived writers
  335. to be XML 1.0 or 1.1. compliant, i.e. in this mode a StreamException is thrown.</p>
  336. <!-- ...................................................... -->
  337. <h2 id="XML_control_char">My parser claims a control character to be invalid, but it was written with XStream!</h2>
  338. <p>Your parser is probably right! Control characters are only valid as part of XML 1.1. You should add an XML header
  339. declaring this version or use a parser that does not care about this part of the specification (e.g. Xpp3 parser).</p>
  340. <!-- ...................................................... -->
  341. <h2 id="XML_attributes">Why is my element not written as XML attribute although I have configured it?</h2>
  342. <p>You can only write types as attributes that are represented as a single String value and are handled therefore
  343. by SingleValueConverter implementations. If your type is handled by a Converter implementation, the configuration
  344. of XStream to write an attribute (using XStream.useAttributeFor() or @XStreamAsAttribute) is simply ignored.</p>
  345. <!-- ...................................................... -->
  346. <h2 id="XML_attribute_normalization">Why are whitespace characters missing in my attribute values after deserialization?</h2>
  347. <p>This is part of the XML specification and a required functionality for any XML parser called
  348. <a href="http://www.w3.org/TR/2006/REC-xml-20060816/#AVNormalize">attribute value normalization</a>. It cannot
  349. be influenced by XStream. Do not use attributes if your values contain leading or trailing whitespaces, other whitespaces
  350. than blanks, or sequences of whitespaces.</p>
  351. <!-- ...................................................... -->
  352. <h2 id="XML_namespaces">Why does XStream not have any namespace support?</h2>
  353. <p>Not every XML parser supports namespaces and not every XML parser that supports namespaces can be configured
  354. within XStream to use those. Basically namespaces must be supported individually for the different XML parsers and the
  355. only support for namespaces that has currently been implemented in XStream is for the StAX paser. Therefore use and
  356. configure the StaxDriver of XStream to use namespaces.</p>
  357. <!-- ...................................................... -->
  358. <h2 id="XML_xpath_limits">My XML contains XPath expressions in the references, but they seem not to work?</h2>
  359. <p>XStream generates only XPath compliant expressions. These have a very limited syntax and they are the only ones
  360. that can be interpreted at deserialization again, since XStream does not use an XPath interpreter. Therefore there
  361. is no support for attribute selectors, qualified element access with axis names or functions. For real XPath
  362. support you will have to implement your own MarshallingStrategy.</p>
  363. <!-- ...................................................... -->
  364. <h2 id="XML_xpath_nodelist">The XPath expressions in the references do select a list, but not a single node!</h2>
  365. <p>Yes, this is right. However, the result type of an
  366. <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/xpath/XPathExpression.html">XPath expression</a>
  367. evaluation can be defined. A node result from a node list is the lists first node, therefore the XPath of XStream
  368. is compliant. Since XStream does not use a real XPath engine, you do not have to worry about memory consumption or
  369. wasted evaluation time, XStream will always operate on a single node anyway. Since XStream 1.4 you can force
  370. XStream to write XPath expressions that select explicit the single node by using the new modes
  371. XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES or SINGLE_NODE_XPATH_RELATIVE_REFERENCES. Instead of generating a
  372. path like "/doc/list/elem/field" XStream will then generate "/doc[1]/list[1]/elem[1]/field[1]". The two notations
  373. are transparent at deserialization time.</p>
  374. <!-- ****************************************************** -->
  375. <h1 id="JSON">JSON specifics</h1>
  376. <h2 id="JSON_2_drivers">Why are there two JSON driver implementations?</h2>
  377. <p>As always, first for historical reasons! Main difference is that the
  378. <a href="javadoc/com/thoughtworks/xstream/io/json/JettisonMappedXmlDriver.html">JettisonMappedXmlDriver</a> is a
  379. thin wrapper around <a href="http://jettison.codehaus.org">Jettison</a> in combination with the
  380. <a href="javadoc/com/thoughtworks/xstream/io/xml/StaxDriver.html">StaxDriver</a>, while the
  381. <a href="javadoc/com/thoughtworks/xstream/io/json/JsonHierarchicalStreamDriver.html">JsonHierarchicalStreamDriver</a>
  382. uses an own more flexible implementation, but can only be used to generate JSON, deserialization is not implemented.</p>
  383. <h2 id="JSON_Jettison_version">Which versions of Jettison are supported?</h2>
  384. <p>Users of Java 5 or higher can use Jettison 1.2 or higher, users of Java 1.4.2 have to use Jettison 1.0.1. Java
  385. 1.3 and Jettison 1.1 is not supported.</p>
  386. <h2 id="JSON_deserialize_top_level_array">Why is it not possible to deserialize a JSON string starting with an array?</h2>
  387. <p>XStream's implementation to deserialize JSON is based on Jettison and StAX. Jettison implements a XMLStreamReader
  388. of StaX and transforms the processed JSON virtually into XML first. However, if the JSON string starts with an array it is not
  389. possible for Jettison to create a valid root element, since it has no name.</p>
  390. <h2 id="JSON_unmarshalling_fails">XStream fails to unmarshal my JSON string and I do not know why?</h2>
  391. <p>Deserialization of JSON is currently done by Jettison, that transforms the JSON string into a StAX stream.
  392. XStream itself does nothing know about the JSON format here. If your JSON string reaches some kind of
  393. complexity and you do not know how to design your Java objects and configure XStream to match those,
  394. you should have a look at the intermediate XML that is processed by XStream in the end. This might help to
  395. identify the problematic spots. Also consider then <a href="#XML_unmarshalling_fails">marshalling your Java
  396. objects into XML first</a>. You can use following code to generate the XML:</p>
  397. <div class="Source Java"><pre>String json = "{\"string\": \"foo\"}";
  398. HierarchicalStreamDriver driver = new JettisonMappedXmlDriver();
  399. StringReader reader = new StringReader(json);
  400. HierarchicalStreamReader hsr = driver.createReader(reader);
  401. StringWriter writer = new StringWriter();
  402. new HierarchicalStreamCopier().copy(hsr, new PrettyPrintWriter(writer));
  403. writer.close();
  404. System.out.println(writer.toString());
  405. </pre></div>
  406. <h2 id="JSON_limitations">What limitations has XStream's JSON support?</h2>
  407. <p>JSON represents a very simple data model for easy data transfer. Especially it has no equivalent for XML
  408. attributes. Those are written with a leading &quot;@&quot; character, but this is not always possible without
  409. violating the syntax (e.g. for array types). Those may silently dropped (and makes it therefore difficult to
  410. implement deserialization). References are another issue in the serialized object graph, since JSON has no
  411. possibility to express such a construct. You should therefore always set the NO_REFERENCES mode of XStream.
  412. Additionally you cannot use implicit collections, since the properties in a JSON object must have unique names.</p>
  413. <h2 id="JSON_encoding">Why are there invalid characters in my JSON representation?</h2>
  414. <p>The JSON spec requires any JSON string to be in UTF-8 encoding. However, XStream ensures this only if you
  415. provide an InputStream or an OutputStream. If you provide a Reader or Writer you have to ensure this requirement
  416. on your own.</p>
  417. <h2 id="JSON_dashes">The generated JSON is invalid, it contains a dash in the label!</h2>
  418. <p>Well, no, the JSON is valid! Please check yourself with the <a href="http://www.jslint.com/">JSON syntax checker</a>.
  419. However, some JavaScript libraries silently assume that the JSON labels are valid JavaScript identifiers, because JavaScript
  420. supports a convenient way to address an element, <strong>if</strong> the label is a valid JavaScript identifier:</p>
  421. <div class="Source JavaScript"><pre>var json = {"label": "foo", "label-with-dash": "bar"};
  422. var fooVar = json.label; // works for labels that are JavaScript identifiers
  423. var barVar = json["label-with-dash"]; // using an array index works always
  424. </pre></div>
  425. <p>As alternative you may wrap the JsonWriter and replace any dash with an underscore:</p>
  426. <div class="Source Java"><pre>HierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver() {
  427. public HierarchicalStreamWriter createWriter(Writer out) {
  428. return new WriterWrapper(super.createWriter(out)) {
  429. public void startNode(String name) {
  430. startNode(name, null);
  431. }
  432. public void startNode(String name, Class clazz) {
  433. wrapped.startNode(name.replace('-', '_'), clazz);
  434. }
  435. }
  436. }
  437. };
  438. XStream xstream = new XStream(driver);
  439. </pre></div>
  440. <!-- ****************************************************** -->
  441. <h1 id="Other_Products">Comparison to other products</h1>
  442. <!-- ...................................................... -->
  443. <h2 id="Other_Products_XMLBeanEncoder">How does XStream compare to java.beans.XMLEncoder?</h2>
  444. <p>XStream is designed for serializing <i>objects</i> using internal fields, whereas
  445. <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLEncoder.html">XMLEncoder</a> is designed for
  446. serializing <i>JavaBeans</i> using public API methods (typically in the form
  447. of <code>getXXX()</code>, <code>setXXX()</code>, <code>addXXX()</code> and <code>removeXXX()</code> methods.</p>
  448. <h2 id="Other_Products_JAXB">How does XStream compare to JAXB (Java API for XML Binding)?</h2>
  449. <p>JAXB is a Java binding tool. It generates Java code from a schema and you are able to transform from those classes into
  450. XML matching the processed schema and back. Note, that you cannot use your own objects, you have to use what is
  451. generated.</p>
  452. <!--
  453. <h1>Comparison to other products</h1>
  454. <h2>How does XStream compare to JAXB (Java API for XML Binding)?</h2>
  455. <p>Todo...</p>
  456. <h2>How does XStream compare to JSX?</h2>
  457. <p>Todo...</p>
  458. <h2>How does XStream compare to Betwixt?</h2>
  459. <p>Todo...</p>
  460. <h2>How does XStream compare to Castor?</h2>
  461. <p>Todo...</p>
  462. <h2>How does XStream compare to Electric XML?</h2>
  463. <p>Todo...</p>
  464. <h2>How does XStream compare to JOX?</h2>
  465. <p>Todo...</p>
  466. <h2>How does XStream compare to JIBX?</h2>
  467. <p>Todo...</p>
  468. -->
  469. <!-- ****************************************************** -->
  470. <h1 id="Scalability">Scalability</h1>
  471. <!-- ...................................................... -->
  472. <h2 id="Scalability_Thread_safety">Is XStream thread safe?</h2>
  473. <p>Yes. Once the XStream instance has been created and configured, it may be shared across multiple threads
  474. allowing objects to be serialized/deserialized concurrently (unless you enable the auto.detection and processing of
  475. annotations). Actually the creation and initialization of XStream is quite expensive, therefore it is recommended to
  476. keep the XStream instance itself.</p>
  477. <!-- ...................................................... -->
  478. <h2 id="Scalability_Memory">How much memory does XStream consume?</h2>
  479. <p>This cannot be answered in general, but following topics have impact on the memory:</p>
  480. <ol>
  481. <li>XML parser technology in use: You should use a streaming parser like Xpp3 or StAX. DOM-based
  482. parsers process the complete XML and create their document model in memory before the first converter of XStream
  483. is called.</li>
  484. <li>Your object model: Is it necessary to keep the complete object graph in memory at once. As alternative you might
  485. use <a href="objectstream.html">object streams</a> or write custom converters that can load and save objects of your
  486. object model on the fly without adding them to the object graph physically. As example see the implementation of the
  487. <a href="javadoc/com/thoughtworks/xstream/persistence/XmlArrayList.html">XmlArrayList</a> in combination with the
  488. <a href="javadoc/com/thoughtworks/xstream/persistence/FileStreamStrategy.html">FileStreamStrategy</a> to keep
  489. parts of the object graph separate.</li>
  490. <li>References: By default XStream supports references to the same object in an object graph. This implies that XStream
  491. keeps track of all serialized and deserialized objects internally. These references are kept with WeakReferences, so that the
  492. memory can be freed as soon as nobody references these objects anymore.</li>
  493. <li>XML values: Any tag and attribute value that is converted into a Java String in the object graph will use the same String
  494. instance.</li>
  495. <li>XStream caches: To increase performance XStream caches quite a lot like classes, converters to use, aliasing, tag names.
  496. All those caches make usage of WeakReferences or will exist only while marshalling one object graph resp. unmarshalling one
  497. input stream.</li>
  498. </ol>
  499. <!-- ...................................................... -->
  500. <h2 id="Scalability_Performance">Can the performance of XStream be increased?</h2>
  501. <p>XStream is a generalizing library, it inspects and handles your types on the fly. Therefore it will normally be slower than
  502. a piece of optimized Java code generated out of a schema. However, it is possible to increase the performance anyway:</p>
  503. <ul>
  504. <li>Write custom converters for those of your types that occur very often in your XML.</li>
  505. <li>Keep a configured XStream instance for multiple usage. Creation and initialization is quite expensive compared to the
  506. overhead of XStream when calling marshall or unmarshal.</li>
  507. <li>Use Xpp3 or StAX parsers.</li>
  508. </ul>
  509. <p>Note, you should never try to optimize code for performance simply because you <strong>believe</strong> that you
  510. have detected a bottle neck. Always use proper tools like a profiler to verify where your hotspots are and whether your
  511. optimization was really successful or not.</p>
  512. <!-- ****************************************************** -->
  513. <h1 id="Uses">Uses of XStream</h1>
  514. <!-- ...................................................... -->
  515. <h2 id="Uses_Data_Binding">Is XStream a data binding tool?</h2>
  516. <p>No. It is a serialization tool.</p>
  517. <!-- ...................................................... -->
  518. <h2 id="Uses_Generate_Code">Can XStream generate classes from XSD?</h2>
  519. <p>No. For this kind of work a data binding tool such as <a href="http://xmlbeans.apache.org">XMLBeans</a> is appropriate.</p>
  520. <!-- ...................................................... -->
  521. <h2 id="Uses_No_SAX_Reader">Why is there no SaxReader?</h2>
  522. <p>XStream works on a stream-based parser model, while SAX is event-based. The stream based model implies, that the
  523. caller consumes the individual tokens from the XML parser on demand, while in an event-based model the parser
  524. controls the application flow on its own and will use callbacks to support client processing. The different
  525. architecture makes it therefore impossible for XStream to use an event-driven XML parser.</p>
  526. <br/>
  527. </div>
  528. </div>
  529. <div class="SidePanel" id="left">
  530. <div class="MenuGroup">
  531. <h1>Software</h1>
  532. <ul>
  533. <li><a href="index.html">About XStream</a></li>
  534. <li><a href="news.html">News</a></li>
  535. <li><a href="changes.html">Change History</a></li>
  536. <li><a href="versioning.html">About Versioning</a></li>
  537. </ul>
  538. </div>
  539. <div class="MenuGroup">
  540. <h1>Evaluating XStream</h1>
  541. <ul>
  542. <li><a href="tutorial.html">Two Minute Tutorial</a></li>
  543. <li><a href="graphs.html">Object references</a></li>
  544. <li><a href="manual-tweaking-output.html">Tweaking the Output</a></li>
  545. <li><a href="license.html">License</a></li>
  546. <li><a href="download.html">Download</a></li>
  547. <li><a href="references.html">References</a></li>
  548. <li><a href="parser-benchmarks.html">Parser Benchmarks</a></li>
  549. <li><a href="http://www.ohloh.net/projects/3459">Code Statistics</a></li>
  550. </ul>
  551. </div>
  552. <div class="MenuGroup">
  553. <h1>Using XStream</h1>
  554. <ul>
  555. <li><a href="architecture.html">Architecture Overview</a></li>
  556. <li><a href="converters.html">Converters</a></li>
  557. <li class="currentLink">Frequently Asked Questions</li>
  558. <li><a href="list-user.html">Users' Mailing List</a></li>
  559. <li><a href="issues.html">Reporting Issues</a></li>
  560. </ul>
  561. </div>
  562. <div class="MenuGroup">
  563. <h1>Javadoc</h1>
  564. <ul>
  565. <li><a href="javadoc/index.html">XStream Core</a></li>
  566. <li><a href="hibernate-javadoc/index.html">Hibernate Extensions</a></li>
  567. <li><a href="benchmark-javadoc/index.html">Benchmark Module</a></li>
  568. </ul>
  569. </div>
  570. <div class="MenuGroup">
  571. <h1>Tutorials</h1>
  572. <ul>
  573. <li><a href="tutorial.html">Two Minute Tutorial</a></li>
  574. <li><a href="alias-tutorial.html">Alias Tutorial</a></li>
  575. <li><a href="annotations-tutorial.html">Annotations Tutorial</a></li>
  576. <li><a href="converter-tutorial.html">Converter Tutorial</a></li>
  577. <li><a href="objectstream.html">Object Streams Tutorial</a></li>
  578. <li><a href="persistence-tutorial.html">Persistence API Tutorial</a></li>
  579. <li><a href="json-tutorial.html">JSON Tutorial</a></li>
  580. </ul>
  581. </div>
  582. <div class="MenuGroup">
  583. <h1>Developing XStream</h1>
  584. <ul>
  585. <li><a href="how-to-contribute.html">How to Contribute</a></li>
  586. <li><a href="list-dev.html">Developers' Mailing List</a></li>
  587. <li><a href="team.html">Development Team</a></li>
  588. <li><a href="repository.html">Source Repository</a></li>
  589. <li><a href="http://bamboo.ci.codehaus.org/browse/XSTREAM">Continuous Integration</a></li>
  590. </ul>
  591. </div>
  592. </div>
  593. </body>
  594. </html>