2011-05-30 90 views
4

我正在Java中使用xStream來從java庫序列化java對象並在客戶端反序列化它。用於序列化和反序列化的xstream錯誤

我有幾個問題:

如果我不喜歡這樣寫道:

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"> 

所以任何建議?

在此先感謝。

+0

請問您可以發佈您正在序列化的課程嗎? – artplastika 2011-05-30 11:56:19

+0

嗨,正如我所提到的,我沒有類結構,它是在一個Java庫中。 – olidev 2011-05-30 12:00:54

+0

看看是否有幫助http://stackoverflow.com/questions/1524775/error-reading-settings-xml它出現有一段時期(。)造成破壞 – Sean 2011-05-30 12:00:54

回答

7

所以這裏忽略的是你如何閱讀文件。您正在使用

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

哪個是週期(。)來自錯誤的地方。來自XML的方法期望實際的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.我能夠複製這個問題,並用上面的方法修復它

+0

嗨肖恩,謝謝。我只是試過了你從BufferedReader中讀取的方法,但它仍然是一樣的錯誤。 :( – olidev 2011-05-30 20:08:17

+0

你能發佈你正在閱讀的完整方法嗎? – Sean 2011-05-30 20:47:50

+1

我發現,Xstream只適用於:InputStream inputStream = new FileInputStream(dseirFile); – olidev 2011-06-07 13:26:58