PageRenderTime 44ms CodeModel.GetById 20ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

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