java xml字符串反序列化_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.(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结构:

如果是的话,我想听听.提前致谢.

解决方法:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值