Reputation: 43
I have below xml which i want to deserialize in XStream.
<comments>
<B>
<id>1</id>
<name>Name 1</name>
</B>
<C>
<id>2</id>
<name>name 2</name>
<desc>Desc 2</desc>
</C>
<B>
<id>3</id>
<name>name 3</name>
</B>
</comments>
The object hierarchy is as below
@XStreamAlias("comments")
class Comments {
@XStreamImplicit
List<A> a = new ArrayList<A>();
}
@XStreamAlias("A")
class A {
}
@XStreamAlias("B")
class B extends A {
long id ;
String name;
}
@XStreamAlias("C")
class C extends A {
long id;
String desc;
String name;
}
The Deserialize code that i have is
XStream xstream = new XStream();
xstream.autodetectAnnotations(Boolean.TRUE);
xstream.alias("comments", Comments.class);
String comments= "path to comments xml";
Comments comments = (Comments)xstream.fromXML(new File(path));
While running the above, i get the below exception,
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field test.Comments.B
---- Debugging information ----
field : B
class : test.Comments
required-type : test.Comments
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /comments/B
line number : 2
version : not available
-------------------------------
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.handleUnknownField(AbstractReflectionConverter.java:495)
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:351)
Could anyone pls help me deserialize the above.
It would also be great help if anyone could point out the best place to learn XStream, I have been searching throughout net for any reference material but apart the XStreams homepage, i dont see anyone talk abt advanced topics.
Thanks
Upvotes: 3
Views: 2798
Reputation: 1146
Annotations are meant for serialization, not for de-serialization. You can leave the annotations out and use the following:
XStream xstream = new XStream();
xstream.alias("comments", ArrayList.class);
xstream.alias("B", B.class);
xstream.alias("C", C.class);
xstream.alias("A", A.class);
Object o = xstream.fromXML(in);
The result will be a list with A, B or C objects depending on the element name.
Upvotes: 5