Search code examples
javaxmlxstream

XStream fail on trivial xml


I have very simple xml file:

testSimple2.txt

<root>
  <document>
  </document>
</root>

But for some reason I can't deserialize it with XStream.

Root.java

@XStreamAlias("root")
public class Root {

 @XStreamAlias("document")
 static public class Document {
 }
 @XStreamAlias("document")
 Document document;

}

Main.java

Main code:

XStream xstream = new XStream();
xstream.autodetectAnnotations(true);
xstream.processAnnotations(Root.class);
Root newJoe = (Root) xstream.fromXML(new File("testSimple2.txt"), Root.class); //Exception here

The following exception is thrown.

com.thoughtworks.xstream.converters.ConversionException: Element document of type verySimple.Root$Document is not defined as field in type java.lang.Class
---- Debugging information ----
class               : verySimple.Root
required-type       : verySimple.Root
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path                : /root/document
line number         : 3
version             : null
-------------------------------
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.writeValueToImplicitCollection(AbstractReflectionConverter.java:403)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:334)
    at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:234)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
    at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
    at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
    at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1058)
    at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1042)
    at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1006)
    at verySimple.RootProcess.main(RootProcess.java:26)

I know there must be some simple mistake, but I can't see it. Please, help.


Solution

  • I can't believe I made this mistake. It is in 4th line:

    Root newJoe = (Root) xstream.fromXML(new File("testSimple2.txt"));
    

    All I needed was just delete "Root.class", or replace it with instance. One more reason to check method signature and documentation before googling and posting such questions...