Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 中XML和對象轉換利器Xstream的使用

android 中XML和對象轉換利器Xstream的使用

編輯:關於Android編程

XStream框架: 雖說pull dom dom4j等優秀的xml解析工具使用非常廣泛,但對於復雜龐大的數據交互來說,使用它們無疑讓你倍加痛苦,你可能大部分精力都放在無聊繁瑣的解析和拼裝上,如果接口稍微改動,更令你有股辭職不相干的沖動,或許你更傾向選擇JSON,但有時候你還是不得不面對JSON,XML,對象之間的轉化的煩惱,如何用最簡單的辦法一統混亂的局面,讓你全心全意做設計寫業務?現在有了XStream,一切將變得美好,永遠告別原始手工作坊,讓你輕松的享受coding帶來的快樂 xStream可以輕易的將Java對象和xml文檔相互轉換,而且可以修改某個特定的屬性和節點名稱,而且也支持json的轉換;  json-lib這個框架 ,Jackson這個框架, 它們都完美支持JSON,但是對xml的支持還不是很好。一定程度上限制了對Java對象的描述,不能讓xml完全體現到對Java對象的描述。這裡將會介紹xStream對JSON、XML的完美支持。xStream不僅對XML的轉換非常友好,而且提供annotation注解,可以在JavaBean中完成對xml節點、屬性的描述。以及對JSON也支持,只需要提供相關的JSONDriver就可以完成轉換。     一.准備環境 首先去 Xstream官方網址 下載最新的jar包,此jar包可以再java和android環境下都適用 二.測試用例代碼 package com.hoo.test;   import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.codehaus.jettison.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hoo.entity.Birthday; import com.hoo.entity.Classes; import com.hoo.entity.ListBean; import com.hoo.entity.Student; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; import com.thoughtworks.xstream.io.json.JsonWriter;   /**  * <b>function:</b>Java對象和XML字符串的相互轉換  * jar-lib-version: xstream-1.3.1  * @author hoojo  * @createDate Nov 27, 2010 12:15:15 PM  * @file XStreamTest.java  * @package com.hoo.test  * @project WebHttpUtils  * @blog http://blog.csdn.net/IBM_hoojo  * @email [email protected]  * @version 1.0  */ @SuppressWarnings("unchecked") public class XStreamTest {          private XStream xstream = null;     private ObjectOutputStream  out = null;     private ObjectInputStream in = null;          private Student bean = null;          /**      * <b>function:</b>初始化資源准備      * @author hoojo      * @createDate Nov 27, 2010 12:16:28 PM      */     @Before     public void init() {         try {             xstream = new XStream();             //xstream = new XStream(new DomDriver()); // 需要xpp3 jar         } catch (Exception e) {             e.printStackTrace();         }         bean = new Student();         bean.setAddress("china");         bean.setEmail("[email protected]");         bean.setId(1);         bean.setName("jack");         Birthday day = new Birthday();         day.setBirthday("2010-11-22");         bean.setBirthday(day);     }          /**      * <b>function:</b>釋放對象資源      * @author hoojo      * @createDate Nov 27, 2010 12:16:38 PM      */     @After     public void destory() {         xstream = null;         bean = null;         try {             if (out != null) {                 out.flush();                 out.close();             }             if (in != null) {                 in.close();             }         } catch (IOException e) {             e.printStackTrace();         }         System.gc();     }          public final void fail(String string) {         System.out.println(string);     }          public final void failRed(String string) {         System.err.println(string);     } } 通過XStream對象的toXML方法就可以完成Java對象到XML的轉換,toXML方法還有2個相同簽名的方法,需要傳遞一個流。然後通過流來完成xml信息的輸出。 3、 需要的JavaBean package com.hoo.entity;   public class Student {     private int id;     private String name;     private String email;     private String address;     private Birthday birthday;     //getter、setter     public String toString() {         return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;     } } 二、Java轉換成XML 1、 JavaBean轉換XM /**  * <b>function:</b>Java對象轉換成XML字符串  * @author hoojo  * @createDate Nov 27, 2010 12:19:01 PM  */ @Test public void writeBean2XML() {     try {         fail("------------Bean->XML------------");         fail(xstream.toXML(bean));         fail("重命名後的XML");         //類重命名         //xstream.alias("account", Student.class);         //xstream.alias("生日", Birthday.class);         //xstream.aliasField("生日", Student.class, "birthday");         //xstream.aliasField("生日", Birthday.class, "birthday");         //fail(xstream.toXML(bean));         //屬性重命名         xstream.aliasField("郵件", Student.class, "email");         //包重命名         xstream.aliasPackage("hoo", "com.hoo.entity");         fail(xstream.toXML(bean));     } catch (Exception e) {         e.printStackTrace();     } } 看結果中的第一份xml內容,是沒有經過然後修改或重命名的文檔,按照原樣輸出。文檔中的第二份文檔的package經過重命名,email屬性也經過重命名以及類名也可以進行重命名的。 運行後結果如下: ------------Bean->XML------------ <com.hoo.entity.Student>   <id>1</id>   <name>jack</name>   <email>[email protected]</email>   <address>china</address>   <birthday>     <birthday>2010-11-22</birthday>   </birthday> </com.hoo.entity.Student> 重命名後的XML <hoo.Student>   <id>1</id>   <name>jack</name>   <郵件>[email protected]</郵件>   <address>china</address>   <birthday>     <birthday>2010-11-22</birthday>   </birthday> </hoo.Student> 2、 將List集合轉換成xml文檔 /**  * <b>function:</b>將Java的List集合轉換成XML對象  * @author hoojo  * @createDate Nov 27, 2010 12:20:07 PM  */ @Test public void writeList2XML() {     try {         //修改元素名稱         xstream.alias("beans", ListBean.class);         xstream.alias("student", Student.class);         fail("----------List-->XML----------");         ListBean listBean = new ListBean();         listBean.setName("this is a List Collection");                  List<Object> list = new ArrayList<Object>();         list.add(bean);         list.add(bean);//引用bean         //list.add(listBean);//引用listBean,父元素                  bean = new Student();         bean.setAddress("china");         bean.setEmail("[email protected]");         bean.setId(2);         bean.setName("tom");         Birthday day = new Birthday("2010-11-22");         bean.setBirthday(day);                  list.add(bean);         listBean.setList(list);                  //將ListBean中的集合設置空元素,即不顯示集合元素標簽         //xstream.addImplicitCollection(ListBean.class, "list");                  //設置reference模型         //xstream.setMode(XStream.NO_REFERENCES);//不引用         xstream.setMode(XStream.ID_REFERENCES);//id引用         //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//絕對路徑引用                    //將name設置為父類(Student)的元素的屬性         xstream.useAttributeFor(Student.class, "name");         xstream.useAttributeFor(Birthday.class, "birthday");         //修改屬性的name         xstream.aliasAttribute("姓名", "name");         xstream.aliasField("生日", Birthday.class, "birthday");                fail(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.addImplicitCollection(ListBean.class, "list"); 這個設置的話,會出現一個List節點包裹著Student節點元素。添加addImplicitCollection可以忽略這個list節點元素。那麼上面的list節點就不存在,只會在beans元素中出現name、student這2個xml元素標簽; setMode是設置相同的對象的引用方式,如果設置XStream.NO_REFERENCES就是不引用,會輸出2分相同的Student元素。如果是XStream.ID_REFERENCES會引用相同的那個對象的id屬性,如果是XStream.XPATH_ABSOLUTE_REFERENCES引用,那麼它將顯示xpath路徑。上面采用的id引用,<student reference="3"/>這個引用了id=3的那個student標簽元素; useAttributeFor是設置某個節點顯示到父節點的屬性中,也就是將指定class中的指定屬性,在這個class元素節點的屬性中顯示。 如:<student><name>hoojo</name></student> 設置好後就是這樣的結果:<student name=”hoojo”></student> aliasAttribute是修改屬性名稱。 3、 在JavaBean中添加Annotation注解進行重命名設置 先看看JavaBean的代碼 package com.hoo.entity;   import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamImplicit; import com.thoughtworks.xstream.annotations.XStreamOmitField;   @XStreamAlias("class") public class Classes {          /*      * 設置屬性顯示      */     @XStreamAsAttribute     @XStreamAlias("名稱")     private String name;          /*      * 忽略      */     @XStreamOmitField     private int number;          @XStreamImplicit(itemFieldName = "Students")     private List<Student> students;          @SuppressWarnings("unused")     @XStreamConverter(SingleValueCalendarConverter.class)     private Calendar created = new GregorianCalendar();            public Classes(){}     public Classes(String name, Student... stu) {         this.name = name;         this.students = Arrays.asList(stu);     }     //getter、setter } SingleValueCalendarConverter.java這個是一個類型轉換器 package com.hoo.entity;   import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter;   public class SingleValueCalendarConverter implements Converter {      public void marshal(Object source, HierarchicalStreamWriter writer,                 MarshallingContext context) {             Calendar calendar = (Calendar) source;             writer.setValue(String.valueOf(calendar.getTime().getTime()));         }           public Object unmarshal(HierarchicalStreamReader reader,                 UnmarshallingContext context) {             GregorianCalendar calendar = new GregorianCalendar();             calendar.setTime(new Date(Long.parseLong(reader.getValue())));             return calendar;         }           @SuppressWarnings("unchecked")         public boolean canConvert(Class type) {             return type.equals(GregorianCalendar.class);         } } 再看看測試用例代碼 @Test public void writeList2XML4Annotation() {     try {         failRed("---------annotation Bean --> XML---------");         Student stu = new Student();         stu.setName("jack");         Classes c = new Classes("一班", bean, stu);         c.setNumber(2);         //對指定的類使用Annotation         //xstream.processAnnotations(Classes.class);         //啟用Annotation         //xstream.autodetectAnnotations(true);         xstream.alias("student", Student.class);         fail(xstream.toXML(c));     } catch (Exception e) {         e.printStackTrace();     } } 當啟用annotation或是對某個特定的類啟用annotation時,上面的classes這個類才有效果。如果不啟用annotation,運行後結果如下: ---------annotation Bean --> XML--------- <com.hoo.entity.Classes>   <name>一班</name>   <number>2</number>   <students class="java.util.Arrays$ArrayList">     <a class="student-array">       <student>         <id>1</id>         <name>jack</name>         <email>[email protected]</email>         <address>china</address>         <birthday>           <birthday>2010-11-22</birthday>         </birthday>       </student>       <student>         <id>0</id>         <name>jack</name>       </student>     </a>   </students>   <created>     <time>1303292056718</time>     <timezone>Asia/Shanghai</timezone>   </created> </com.hoo.entity.Classes> 當啟用annotation後xstream.processAnnotations(Classes.class),結果如下: ---------annotation Bean --> XML--------- <class 名稱="一班">   <Students>     <id>1</id>     <name>jack</name>     <email>[email protected]</email>     <address>china</address>     <birthday>       <birthday>2010-11-22</birthday>     </birthday>   </Students>   <Students>     <id>0</id>     <name>jack</name>   </Students>   <created>1303292242937</created> </class> 4、 Map集合轉換xml文檔 /**  * <b>function:</b>Java Map集合轉XML  * @author hoojo  * @createDate Nov 27, 2010 1:13:26 PM  */ @Test public void writeMap2XML() {     try {         failRed("---------Map --> XML---------");         Map<String, Student> map = new HashMap<String, Student>();         map.put("No.1", bean);//put                  bean = new Student();         bean.setAddress("china");         bean.setEmail("[email protected]");         bean.setId(2);         bean.setName("tom");         Birthday day = new Birthday("2010-11-22");         bean.setBirthday(day);         map.put("No.2", bean);//put                  bean = new Student();         bean.setName("jack");         map.put("No.3", bean);//put                  xstream.alias("student", Student.class);         xstream.alias("key", String.class);         xstream.useAttributeFor(Student.class, "id");         xstream.useAttributeFor("birthday", String.class);         fail(xstream.toXML(map));     } catch (Exception e) {         e.printStackTrace();     } } 運行後結果如下: ---------Map --> XML--------- <map>   <entry>     <key>No.3</key>     <student id="0">       <name>jack</name>     </student>   </entry>   <entry>     <key>No.1</key>     <student id="1">       <name>jack</name>       <email>[email protected]</email>       <address>china</address>       <birthday birthday="2010-11-22"/>     </student>   </entry>   <entry>     <key>No.2</key>     <student id="2">       <name>tom</name>       <email>[email protected]</email>       <address>china</address>       <birthday birthday="2010-11-22"/>     </student>   </entry> </map> 5、 用OutStream輸出流寫XML /**  * <b>function:</b>用OutStream輸出流寫XML  * @author hoojo  * @createDate Nov 27, 2010 1:13:48 PM  */ @Test public void writeXML4OutStream() {     try {         out = xstream.createObjectOutputStream(System.out);         Student stu = new Student();         stu.setName("jack");         Classes c = new Classes("一班", bean, stu);         c.setNumber(2);         failRed("---------ObjectOutputStream # JavaObject--> XML---------");         out.writeObject(stu);         out.writeObject(new Birthday("2010-05-33"));         out.write(22);//byte         out.writeBoolean(true);         out.writeFloat(22.f);         out.writeUTF("hello");              } catch (Exception e) {         e.printStackTrace();     } } 使用輸出流後,可以通過流對象完成xml的構建,即使沒有JavaBean對象,你可以用流來構建一個復雜的xml文檔,運行後結果如下: ---------ObjectOutputStream # JavaObject--> XML--------- <object-stream>   <com.hoo.entity.Student>     <id>0</id>     <name>jack</name>   </com.hoo.entity.Student>   <com.hoo.entity.Birthday>     <birthday>2010-05-33</birthday>   </com.hoo.entity.Birthday>   <byte>22</byte>   <boolean>true</boolean>   <float>22.0</float>   <string>hello</string> </object-stream> 三、XML內容轉換Java對象 1、 用InputStream將XML文檔轉換成java對象 /**  * <b>function:</b>用InputStream將XML文檔轉換成java對象   * 需要額外的jar xpp3-main.jar  * @author hoojo  * @createDate Nov 27, 2010 1:14:52 PM  */ @Test public void readXML4InputStream() {     try {         String s = "<object-stream><com.hoo.entity.Student><id>0</id><name>jack</name>" +           "</com.hoo.entity.Student><com.hoo.entity.Birthday><birthday>2010-05-33</birthday>" +           "</com.hoo.entity.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" +           "<string>hello</string></object-stream>";         failRed("---------ObjectInputStream## XML --> javaObject---------");         StringReader reader = new StringReader(s);         in = xstream.createObjectInputStream(reader);         Student stu = (Student) in.readObject();         Birthday b = (Birthday) in.readObject();         byte i = in.readByte();         boolean bo = in.readBoolean();         float f = in.readFloat();         String str = in.readUTF();         System.out.println(stu);         System.out.println(b);         System.out.println(i);         System.out.println(bo);         System.out.println(f);         System.out.println(str);     } catch (Exception e) {         e.printStackTrace();     } } 讀取後,轉換的Java對象,結果如下: ---------ObjectInputStream## XML --> javaObject--------- jack#0#null#null#null 2010-05-33 22 true 22.0 hello 2、 將xml文檔轉換成Java對象 /**  * <b>function:</b>將XML字符串轉換成Java對象  * @author hoojo  * @createDate Nov 27, 2010 2:39:06 PM  */ @Test public void readXml2Object() {     try {         failRed("-----------Xml >>> Bean--------------");         Student stu = (Student) xstream.fromXML(xstream.toXML(bean));         fail(stu.toString());                  List<Student> list = new ArrayList<Student>();         list.add(bean);//add                  Map<String, Student> map = new HashMap<String, Student>();         map.put("No.1", bean);//put                  bean = new Student();         bean.setAddress("china");         bean.setEmail("[email protected]");         bean.setId(2);         bean.setName("tom");         Birthday day = new Birthday("2010-11-22");         bean.setBirthday(day);         list.add(bean);//add         map.put("No.2", bean);//put                  bean = new Student();         bean.setName("jack");         list.add(bean);//add         map.put("No.3", bean);//put                  failRed("==========XML >>> List===========");         List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));         fail("size:" + studetns.size());//3         for (Student s : studetns) {             fail(s.toString());         }                  failRed("==========XML >>> Map===========");         Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));         fail("size:" + maps.size());//3         Set<String> key = maps.keySet();         Iterator<String> iter = key.iterator();         while (iter.hasNext()) {             String k = iter.next();             fail(k + ":" + map.get(k));         }     } catch (Exception e) {         e.printStackTrace();     } } 運行後結果如下: -----------Xml >>> Bean-------------- jack#1#china#2010-11-22#[email protected] ==========XML >>> List=========== size:3 jack#1#china#2010-11-22#[email protected] tom#2#china#2010-11-22#[email protected] jack#0#null#null#null ==========XML >>> Map=========== size:3 No.3:jack#0#null#null#null No.1:jack#1#china#2010-11-22#[email protected] No.2:tom#2#china#2010-11-22#[email protected] 怎麼樣,成功的完成XML到JavaBean、List、Map的轉換,更多對象轉換還需要大家一一嘗試。用法類似~這裡就不一樣贅述。 四、XStream對JSON的支持 xStream對JSON也有非常好的支持,它提供了2個模型驅動。用這2個驅動可以完成Java對象到JSON的相互轉換。使用JettisonMappedXmlDriver驅動,將Java對象轉換成json,需要添加jettison.jar 1、 用JettisonMappedXmlDriver完成Java對象到JSON的轉換 /**  * <b>function:</b>XStream結合JettisonMappedXmlDriver驅動,轉換Java對象到JSON  * 需要添加jettison jar  * @author hoojo  * @createDate Nov 27, 2010 1:23:18 PM  */ @Test public void writeEntity2JETTSON() {     failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString=========");     xstream = new XStream(new JettisonMappedXmlDriver());     xstream.setMode(XStream.NO_REFERENCES);     xstream.alias("student", Student.class);     fail(xstream.toXML(bean)); } 運行後結果如下: =======JettisonMappedXmlDriver===JavaObject >>>> JaonString========= {"student":{"id":1,"name":"jack","email":"[email protected]","address":"china","birthday":[{},"2010-11-22"]}} JSON的轉換和XML的轉換用法一樣,只是創建XStream需要傳遞一個參數,這個參數就是xml到JSON映射轉換的驅動。這裡會降到兩個驅動,分別是JettisonMappedXmlDriver、JsonHierarchicalStreamDriver。 2、 JsonHierarchicalStreamDriver完成Java對象到JSON的轉換 /**  * <b>function:</b>用XStream結合JsonHierarchicalStreamDriver驅動  * 轉換java對象為JSON字符串  * @author hoojo  * @createDate Nov 27, 2010 1:16:46 PM  */ @Test public void writeEntiry2JSON() {     failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");     xstream = new XStream(new JsonHierarchicalStreamDriver());     //xstream.setMode(XStream.NO_REFERENCES);     xstream.alias("student", Student.class);     failRed("-------Object >>>> JSON---------");     fail(xstream.toXML(bean));          //failRed("========JsonHierarchicalStreamDriver==刪除根節點=========");     //刪除根節點     xstream = new XStream(new JsonHierarchicalStreamDriver() {         public HierarchicalStreamWriter createWriter(Writer out) {             return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);         }     });     //xstream.setMode(XStream.NO_REFERENCES);     xstream.alias("student", Student.class);     fail(xstream.toXML(bean)); } 運行後結果如下: ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= -------Object >>>> JSON--------- {"student": {   "id": 1,   "name": "jack",   "email": "[email protected]",   "address": "china",   "birthday": {     "birthday": "2010-11-22"   } }} {   "id": 1,   "name": "jack",   "email": "[email protected]",   "address": "china",   "birthday": {     "birthday": "2010-11-22"   } } 使用JsonHierarchicalStreamDriver轉換默認會給轉換後的對象添加一個根節點,但是在構建JsonHierarchicalStreamDriver驅動的時候,你可以重寫createWriter方法,刪掉根節點。 看上面的結果,一個是默認帶根節點的JSON對象,它只是將類名作為一個屬性,將對象作為該屬性的一個值。而另一個沒有帶根屬性的JSON就是通過重寫createWriter方法完成的。 3、 將List集合轉換成JSON字符串 @Test public void writeList2JSON() {     failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");     JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();     xstream = new XStream(driver);     //xstream = new XStream(new JettisonMappedXmlDriver());//轉換錯誤     //xstream.setMode(XStream.NO_REFERENCES);     xstream.alias("student", Student.class);          List<Student> list = new ArrayList<Student>();     list.add(bean);//add          bean = new Student();     bean.setAddress("china");     bean.setEmail("[email protected]");     bean.setId(2);     bean.setName("tom");     Birthday day = new Birthday("2010-11-22");     bean.setBirthday(day);     list.add(bean);//add          bean = new Student();     bean.setName("jack");     list.add(bean);//add          fail(xstream.toXML(list));          //failRed("========JsonHierarchicalStreamDriver==刪除根節點=========");     //刪除根節點     xstream = new XStream(new JsonHierarchicalStreamDriver() {         public HierarchicalStreamWriter createWriter(Writer out) {             return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);         }     });     xstream.alias("student", Student.class);     fail(xstream.toXML(list)); } 運行後結果如下 ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= ##{"list": [   {     "id": 1,     "name": "jack",     "email": "[email protected]",     "address": "china",     "birthday": {       "birthday": "2010-11-22"     }   },   {     "id": 2,     "name": "tom",     "email": "[email protected]",     "address": "china",     "birthday": {       "birthday": "2010-11-22"     }   },   {     "id": 0,     "name": "jack"   } ]} #[   {     "id": 1,     "name": "jack",     "email": "[email protected]",     "address": "china",     "birthday": {       "birthday": "2010-11-22"     }   },   {     "id": 2,     "name": "tom",     "email": "[email protected]",     "address": "china",     "birthday": {       "birthday": "2010-11-22"     }   },   {     "id": 0,     "name": "jack"   } ] 上面的list1是使用JsonHierarchicalStreamDriver 轉換的,當然你也可以使用JettisonMappedXmlDriver驅動進行轉換;用JettisonMappedXmlDriver轉換後,你會發現格式不同而且沒有根屬性。 4、 Map轉換json @Test public void writeMap2JSON() {     failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========");     xstream = new XStream(new JsonHierarchicalStreamDriver());     //xstream = new XStream(new JettisonMappedXmlDriver());     xstream.alias("student", Student.class);          Map<String, Student> map = new HashMap<String, Student>();     map.put("No.1", bean);//put          bean = new Student();     bean.setAddress("china");     bean.setEmail("[email protected]");     bean.setId(2);     bean.setName("tom");     bean.setBirthday(new Birthday("2010-11-21"));     map.put("No.2", bean);//put          bean = new Student();     bean.setName("jack");     map.put("No.3", bean);//put          fail(xstream.toXML(map));          //failRed("========JsonHierarchicalStreamDriver==刪除根節點=========");     //刪除根節點     xstream = new XStream(new JsonHierarchicalStreamDriver() {         public HierarchicalStreamWriter createWriter(Writer out) {             return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);         }     });     xstream.alias("student", Student.class);     fail(xstream.toXML(map)); } 運行後結果如下: ======JsonHierarchicalStreamDriver==== Map >>>> JaonString========= {"map": [   [     "No.3",     {       "id": 0,       "name": "jack"     }   ],   [     "No.1",     {       "id": 1,       "name": "jack",       "email": "[email protected]",       "address": "china",       "birthday": {         "birthday": "2010-11-22"       }     }   ],   [     "No.2",     {       "id": 2,       "name": "tom",       "email": "[email protected]",       "address": "china",       "birthday": {         "birthday": "2010-11-21"       }     }   ] ]} [   [     "No.3",     {       "id": 0,       "name": "jack"     }   ],   [     "No.1",     {       "id": 1,       "name": "jack",       "email": "[email protected]",       "address": "china",       "birthday": {         "birthday": "2010-11-22"       }     }   ],   [     "No.2",     {       "id": 2,       "name": "tom",       "email": "[email protected]",       "address": "china",       "birthday": {         "birthday": "2010-11-21"       }     }   ] ] 5、 將JSON轉換java對象 /**  * <b>function:</b>JsonHierarchicalStreamDriver可以將簡單的json字符串轉換成java對象,list、map轉換不成功;  * JsonHierarchicalStreamDriver讀取JSON字符串到java對象出錯  * @author hoojo  * @createDate Nov 27, 2010 1:22:26 PM  * @throws JSONException  */ @Test public void readJSON2Object() throws JSONException {     String json = "{\"student\": {" +         "\"id\": 1," +         "\"name\": \"haha\"," +         "\"email\": \"email\"," +         "\"address\": \"address\"," +         "\"birthday\": {" +             "\"birthday\": \"2010-11-22\"" +         "}" +     "}}";     //JsonHierarchicalStreamDriver讀取JSON字符串到java對象出錯,但JettisonMappedXmlDriver可以     xstream = new XStream(new JettisonMappedXmlDriver());     xstream.alias("student", Student.class);     fail(xstream.fromXML(json).toString());          //JettisonMappedXmlDriver轉換List集合出錯,但JsonHierarchicalStreamDriver可以轉換正確     //JettisonMappedXmlDriver 轉換的字符串 {"list":{"student":[{"id":1,"name":"haha","email":"email","address":"address","birthday":[{},"2010-11-22"]}]},"student":{"id":2,"name":"tom","email":"[email protected]","address":"china","birthday":[{},"2010-11-22"]}}     json = "{\"list\": [{" +             "\"id\": 1," +             "\"name\": \"haha\"," +             "\"email\": \"email\"," +             "\"address\": \"address\"," +             "\"birthday\": {" +               "\"birthday\": \"2010-11-22\"" +             "}" +            "},{" +             "\"id\": 2," +             "\"name\": \"tom\"," +             "\"email\": \"[email protected]\"," +             "\"address\": \"china\"," +             "\"birthday\": {" +               "\"birthday\": \"2010-11-22\"" +             "}" +           "}]}";     System.out.println(json);//用js轉換成功     List list = (List) xstream.fromXML(json);     System.out.println(list.size());//0好像轉換失敗 } 運行後結果如下: haha#1#address#2010-11-22#email {"list": [{"id": 1,"name": "haha","email": "email","address": "address","birthday": {"birthday": "2010-11-22"}}, {"id": 2,"name": "tom","email": "[email protected]","address": "china","birthday": {"birthday": "2010-11-22"}}]} 0 JSON到Java的轉換是fromXML方法。
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved