xStream框架 html
xStream能夠輕易的將Java對象和xml文檔相互轉換,並且能夠修改某個特定的屬性和節點名稱,並且也支持json的轉換;java
前面有介紹過json-lib這個框架,在線博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html json
以及Jackson這個框架,在線博文:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html app
它們都完美支持JSON,可是對xml的支持還不是很好。必定程度上限制了對Java對象的描述,不能讓xml徹底體現到對Java對象的描述。這裏將會介紹xStream對JSON、XML的完美支持。xStream不只對XML的轉換很是友好,並且提供annotation註解,能夠在JavaBean中完成對xml節點、屬性的描述。以及對JSON也支持,只須要提供相關的JSONDriver就能夠完成轉換。框架
1、準備工做 測試
一、 下載jar包、及官方資源this
xStream的jar下載地址:.net
官方的示例很全,官方參考示例:http://xstream.codehaus.org/tutorial.html xml
添加xstream-1.3.1.jar文件到工程中,就能夠開始下面的工做;須要的jar以下:
二、 測試用例代碼
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 hoojo_@126.com * @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("jack@email.com"); 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信息的輸出。
三、 須要的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; } }
2、Java轉換成XML
一、 JavaBean轉換XML
/** * <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>jack@email.com</email> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </com.hoo.entity.Student>
重命名後的XML
<hoo.Student> <id>1</id> <name>jack</name> <郵件>jack@email.com</郵件> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </hoo.Student>
二、 將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("tom@125.com"); 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>jack@email.com</email> <address>china</address> <birthday id="4" 生日="2010-11-22"/> </student> <student reference="3"/> <student id="5" 姓名="tom"> <id>2</id> <email>tom@125.com</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是修改屬性名稱。
三、 在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>jack@email.com</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>jack@email.com</email> <address>china</address> <birthday> <birthday>2010-11-22</birthday> </birthday> </Students> <Students> <id>0</id> <name>jack</name> </Students> <created>1303292242937</created> </class>
四、 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("tom@125.com"); 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>jack@email.com</email> <address>china</address> <birthday birthday="2010-11-22"/> </student> </entry> <entry> <key>No.2</key> <student id="2"> <name>tom</name> <email>tom@125.com</email> <address>china</address> <birthday birthday="2010-11-22"/> </student> </entry> </map>
五、 用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>
3、XML內容轉換Java對象
一、 用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
二、 將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("tom@125.com"); 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#jack@email.com
==========XML >>> List===========
size:3
jack#1#china#2010-11-22#jack@email.com
tom#2#china#2010-11-22#tom@125.com
jack#0#null#null#null
==========XML >>> Map===========
size:3
No.3:jack#0#null#null#null
No.1:jack#1#china#2010-11-22#jack@email.com
No.2:tom#2#china#2010-11-22#tom@125.com
怎麼樣,成功的完成XML到JavaBean、List、Map的轉換,更多對象轉換還須要你們一一嘗試。用法相似~這裏就不同贅述。
4、XStream對JSON的支持
xStream對JSON也有很是好的支持,它提供了2個模型驅動。用這2個驅動能夠完成Java對象到JSON的相互轉換。使用JettisonMappedXmlDriver驅動,將Java對象轉換成json,須要添加jettison.jar
一、 用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":"jack@email.com","address":"china","birthday":[{},"2010-11-22"]}}
JSON的轉換和XML的轉換用法同樣,只是建立XStream須要傳遞一個參數,這個參數就是xml到JSON映射轉換的驅動。這裏會降到兩個驅動,分別是JettisonMappedXmlDriver、JsonHierarchicalStreamDriver。
二、 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": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }} { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }
使用JsonHierarchicalStreamDriver轉換默認會給轉換後的對象添加一個根節點,可是在構建JsonHierarchicalStreamDriver驅動的時候,你能夠重寫createWriter方法,刪掉根節點。
看上面的結果,一個是默認帶根節點的JSON對象,它只是將類名做爲一個屬性,將對象做爲該屬性的一個值。而另外一個沒有帶根屬性的JSON就是經過重寫createWriter方法完成的。
三、 將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("tom@125.com"); 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": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 0, "name": "jack" } ]} #[ { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 0, "name": "jack" } ]
上面的list1是使用JsonHierarchicalStreamDriver 轉換的,固然你也能夠使用JettisonMappedXmlDriver驅動進行轉換;用JettisonMappedXmlDriver轉換後,你會發現格式不一樣並且沒有根屬性。
四、 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("tom@125.com"); 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": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } } ], [ "No.2", { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-21" } } ] ]} [ [ "No.3", { "id": 0, "name": "jack" } ], [ "No.1", { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } } ], [ "No.2", { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-21" } } ] ]
五、 將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":"tom@125.com","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\": \"tom@125.com\"," + "\"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": "tom@125.com","address": "china","birthday": {"birthday": "2010-11-22"}}]} 0
JSON到Java的轉換是fromXML方法。