gpt4 book ai didi

java - 序列化和反序列化的 xstream 错误

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:17 24 4
gpt4 key购买 nike

我在 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();

=> 我遇到序列化问题: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">

有什么建议吗?

提前致谢。

最佳答案

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

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());

附言我能够重现这个问题,并用上面的方法修复它

关于java - 序列化和反序列化的 xstream 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6175883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com