用于序列化的xstream错误&反序列化

时间:2011-05-30 11:48:46

标签: java xstream

我在Java中使用xStream从java库中序列化java对象并在客户端对其进行反序列化。

我有几个问题:

如果我这样做:

XStream xstream = new XStream();
xstream.setMode(XStream.ID_REFERENCES);
xstream.autodetectAnnotations(true);
Writer writer = new FileWriter(xmlFile);        
writer.write(xstream.toXML(myObject));
writer.close();

=>序列化可以,但反序列化:Exception in thread "main" com.thoughtworks.xstream.io.StreamException: : only whitespace content allowed before start tag and not . (position: START_DOCUMENT seen .... @1:1)

如果我这样做:

XStream xstream = new XStream();
xstream.setMode(XStream.NO_REFERENCES);
xstream.autodetectAnnotations(true);
Writer writer = new FileWriter(xmlFile);        
writer.write(xstream.toXML(myObject));
writer.close();

=&GT;我遇到了序列化问题:Exception in thread "main" com.thoughtworks.xstream.io.StreamException: : only whitespace content allowed before start tag and not . (position: START_DOCUMENT seen .... @1:1) at com.thoughtworks.xstream.io.xml.XppReader.pullNextEvent(XppReader.java:78) at com.thoughtworks.xstream.io.xml.AbstractPullReader.readRealEvent(AbstractPullReader.java:137) at com.thoughtworks.xstream.io.xml.AbstractPullReader.readEvent(AbstractPullReader.java:130) at com.thoughtworks.xstream.io.xml.AbstractPullReader.move(AbstractPullReader.java:109) at com.thoughtworks.xstream.io.xml.AbstractPullReader.moveDown(AbstractPullReader.java:94) at com.thoughtworks.xstream.io.xml.XppReader.<init>(XppReader.java:48) at com.thoughtworks.xstream.io.xml.XppDriver.createReader(XppDriver.java:44) at com.thoughtworks.xstream.XStream.fromXML(XStream.java:853) at com.thoughtworks.xstream.XStream.fromXML(XStream.java:845)

使用xml:

<Test.Platform id="1">
    <TaskImpl id="1">
          <model reference="2"/>
          <name>process</name>
    </TaskImpl>
</Test.Platform id="1">

那么有什么建议吗?

提前致谢。

1 个答案:

答案 0 :(得分:9)

所以这里忽略的是你如何阅读文件。你正在使用

XStream xstream = new XStream();
xstream.fromXML("model.xml");

错误中句点(。)的来源。 fromXML的方法是期望实际的XML输入而不是文件名。因此,当它解析你的xml(它是“model.xml”而不是实际的xml)时,它会给出错误。 XStream的网站现在已经关闭,所以我无法链接到API

使用FileReader / BufferedReader以获取XML的内容。这样的事情应该有效

XStream instream = new XStream();

BufferedReader br = new BufferedReader(new FileReader("model.xml"));
StringBuffer buff = new StringBuffer();
String line;
while((line = br.readLine()) != null){
   buff.append(line);
}
Platform p = (Platform)instream.fromXML(buff.toString());

P.S。我能够复制问题,并用上面的

修复它