使用XStream把Java對象序列化為XML(二)

來源:互聯網
上載者:User

 添加 XStream 支援

    按照下列步驟向建立的項目添加 XStream 庫:

    1. 在 Eclipse 的 Project Explorer 中選擇建立的項目,從 Project 菜單中選擇 Properties(如 圖 5 所示)。

圖 5. 添加 XStream 庫

    2. 單擊 Add External JARs,從 xstream_home/lib 檔案夾中選擇 xstream-1.2.2.jar.

    3. 單擊 OK 結束(如 圖 6 所示)。

圖 6. 完成 XStream 支援的添加

    圖 7 顯示了添加 XStream 支援後的項目。

    序列化對象

    這個簡單的例子示範了如何使用 XStream 序列化/逆序列化對象,包括兩個類:Writer 和 Reader。Writer 類使用 XStream API 把 Employee 類型的對象序列化為 XML 並儲存到檔案中(如 清單 1 所示)。

    清單 1. Writer.java

 

package com.samples;import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.thoughtworks.xstream.*;public class Writer { public static void main(String[] args) { Employee e = new Employee(); //Set the properties using the setter methods //Note: This can also be done with a constructor. //Since we want to show that XStream can serialize //even without a constructor, this approach is used. e.setName("Jack"); e.setDesignation("Manager"); e.setDepartment("Finance"); //Serialize the object XStream xs = new XStream(); //Write to a file in the file system try { FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt"); xs.toXML(e, fs); } catch (FileNotFoundException e1) { e1.printStackTrace(); } }}

 

    Reader 類讀取該檔案,逆序列化 XML 並把資料裝入 Java 對象(如 清單 2 所示)。

引用自:http://java.chinaitlab.com/XMLBeans/777336_2.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.