xStream轉換XML、JSON

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   io   java   ar   

一. 簡介

xStream可以很容易實現Java對象和xml文檔互相轉換, 可以修改某個特定的屬性和節點名稱,xStream提供annotation註解,

可以在JavaBean中完成對xml節點和屬性的描述,並支援Json的轉換,只需要提供相關的JSONDriver就能完成轉換

官方網站: http://xstream.codehaus.org/tutorial.html


二. 準備工作

1. 環境準備:

Jar檔案:

https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/xstream-distribution-1.3.1-bin.zip

代碼結構圖:



2. junit測試代碼:

public class XStreamTest {private XStream xstream;private ObjectOutputStream out;private ObjectInputStream in;private Student student;/** * 初始化資源準備 */@Beforepublic void init() {try {xstream = new XStream(new DomDriver());} catch (Exception e) {e.printStackTrace();}student = new Student();student.setAddress("china");student.setEmail("[email protected]");student.setId(1);student.setName("jack");Birthday birthday = new Birthday(); birthday.setBirthday("2010-11-22");student.setBirthday(birthday);}/** * 釋放對象資源 */@Afterpublic void destory() {xstream = null;student = null;try {if (out != null) {out.flush();out.close();}if (in != null) {in.close();}} catch (IOException e) {e.printStackTrace();}System.gc();}/** * 列印字串 */public final void print(String string) { System.out.println(string);}/** * 高亮字串 */public final void highLight(String string) {System.err.println(string);}}

3. 所需實體類:

(1)Student:

public class Student {private int id;private String name;private String email;private String address;private Birthday birthday;// getter and setterpublic String toString() {return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;}}


(2)Birthday

public class Birthday {private String birthday;public Birthday() {}public Birthday(String birthday) {this.birthday = birthday;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}}

三 Java對象轉為xml

1. 將JavaBean轉成xml文檔:

/**  * Java對象轉換成XML */@Testpublic void writeBean2XML() {try {highLight("====== Bean -> XML ======");print("<!-- 沒有重新命名的XML -->");print(xstream.toXML(student));print("<!-- 重新命名後的XML -->");// 類重新命名xstream.alias("student", Student.class);xstream.alias("生日", Birthday.class);xstream.aliasField("生日", Student.class, "birthday");xstream.aliasField("生日", Birthday.class, "birthday");// 屬性重新命名xstream.aliasField("郵件", Student.class, "email");// 包重新命名xstream.aliasPackage("zdp", "com.zdp.domain");print(xstream.toXML(student));} catch (Exception e) {e.printStackTrace();}}


運行結果:

====== Bean -> XML ======<!-- 沒有重新命名的XML --><com.zdp.domain.Student>  <id>1</id>  <name>jack</name>  <email>[email protected]</email>  <address>china</address>  <birthday>    <birthday>2010-11-22</birthday>  </birthday></com.zdp.domain.Student><!-- 重新命名後的XML --><student>  <id>1</id>  <name>jack</name>  <郵件>[email protected]</郵件>  <address>china</address>  <生日>    <生日>2010-11-22</生日>  </生日></student>

第一份文檔是沒有經過修改或重新命名的文檔, 按照原樣輸出。

第二份文檔的類、屬性、包都經過了重新命名。


2. 將List集合轉成xml文檔:

/** * 將List集合轉換成XML對象 */@Testpublic void writeList2XML() {try {// 修改元素名稱highLight("====== List --> XML ======");xstream.alias("beans", ListBean.class);xstream.alias("student", Student.class);ListBean listBean = new ListBean();listBean.setName("this is a List Collection");List<Object> list = new ArrayList<Object>();// 引用javabeanlist.add(student);list.add(student); // list.add(listBean); 引用listBean,父元素student = new Student();student.setAddress("china");student.setEmail("[email protected]");student.setId(2);student.setName("tom");Birthday birthday = new Birthday("2010-11-22"); student.setBirthday(birthday);list.add(student);listBean.setList(list);// 將ListBean中的集合設定空元素,即不顯示集合元素標籤        // xstream.addImplicitCollection(ListBean.class, "list");// 設定reference模型xstream.setMode(XStream.ID_REFERENCES); // id引用        //xstream.setMode(XStream.NO_REFERENCES); // 不引用        //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); // 絕對路徑引用// 將name設定為父類(Student)的元素的屬性        xstream.useAttributeFor(Student.class, "name");        xstream.useAttributeFor(Birthday.class, "birthday");// 修改屬性的namexstream.aliasAttribute("姓名", "name");xstream.aliasField("生日", Birthday.class, "birthday");print(xstream.toXML(listBean));} catch (Exception e) {e.printStackTrace();}}


運行結果:

====== List --> XML ======<beans id="1">  <name>this is a List Collection</name>  <list id="2">    <student id="3" 姓名="jack">      <id>1</id>      <email>[email protected]</email>      <address>china</address>      <birthday id="4" 生日="2010-11-22"/>    </student>    <student reference="3"/>    <student id="5" 姓名="tom">      <id>2</id>      <email>[email protected]</email>      <address>china</address>      <birthday id="6" 生日="2010-11-22"/>    </student>  </list></beans>







xStream轉換XML、JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.