我有下面的xml,我想在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>
对象层次结构如下
@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;
}
我的反序列化代码是
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));
在运行上述内容时,我得到以下异常,
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)
任何人都可以帮我反编译上面的内容。
如果有人能指出学习XStream的最佳位置,那也是很有帮助的,我一直在网上搜索任何参考资料但除了XStreams主页之外,我没有看到任何人谈论高级主题。
由于
答案 0 :(得分:5)
注释用于序列化,而不是用于反序列化。您可以保留注释并使用以下内容:
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);
结果将是包含A,B或C对象的列表,具体取决于元素名称。