java – 从xstream反序列化xml文件
作者:互联网
我正在使用Xstream来序列化Job对象.它看起来很好用.
但是反序列化,我有一个问题:
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)
你们其中一个人之前遇到过这个问题吗?
这是我为序列化做的方式:
XStream xstream = new XStream();
Writer writer = new FileWriter(new File("model.xml"));
writer.write(xstream.toXML(myModel));
writer.close();
我也试过这个:
XStream xstream = new XStream();
OutputStream out = new FileOutputStream("model.xml");
xstream.toXML(myModel, out);
对于反序列化,我这样做:
XStream xstream = new XStream();
xstream.fromXML("model.xml");
XML结构:
<projectCar.CarImpl>
<CarModel reference="../.."></CarModel>
</projectCar.CarImpl>
如果是的话,我想听听.提前致谢.
解决方法:
fromXML没有文件名,请尝试:
File xmlFile = new File("model.xml");
xstream.fromXML(new FileInputStream(xmlFile));
以字符串形式读取文件内容.
字段名“id”和“reference”也恰好是XStream中的“系统属性”.使用以下代码:
CarImpl myModel = new CarImpl();
File xmlFile = new File("model.xml");
XStream xstream = new XStream();
xstream.useAttributeFor(String.class);
xstream.useAttributeFor(Integer.class);
Writer writer = new FileWriter(xmlFile);
writer.write(xstream.toXML(myModel));
writer.close();
CarImpl fromXML = (CarImpl) xstream.fromXML(new FileInputStream(xmlFile));
System.out.println(fromXML);
如果字段被称为“id”和“reference”,则解组失败,否则成功.见XStream FAQ
查看新方法’aliasForSystemAttribute’以获得可能的解决方案.
标签:xstream,java,deserialization 来源: https://codeday.me/bug/20191008/1873527.html