标签:
一、准备工作
1、 下载jar包、及官方资源
xStream的jar下载地址:https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/xstream-distribution-1.3.1-bin.zip
官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html
添加xstream-1.3.1.jar文件到工程中,就可以开始下面的工作;需要的jar如下:
2、 测试用例代码
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 * @createDate Nov 27, 2010 12:15:15 PM * @file XStreamTest.java * @package com.hoo.test * @project WebHttpUtils * @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>初始化资源准备 * @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>释放对象资源 * @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
1 package com.hoo.entity; 2 3 public class Student { 4 5 private int id; 6 private String name; 7 private String email; 8 private String address; 9 private Birthday birthday; 10 11 //getter、setter 此处省略 12 public String toString() { 13 return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email; 14 } 15 }
1 package com.hoo.entity; 2 3 import java.util.List; 4 5 public class ListBean { 6 7 private String name; 8 private List<Object> list; 9 10 public List<Object> getList() { 11 return list; 12 } 13 public void setList(List<Object> list) { 14 this.list = list; 15 } 16 public String getName() { 17 return name; 18 } 19 20 public void setName(String name) { 21 this.name = name; 22 } 23 }
二、Java转换成XML
1、 JavaBean转换XML
1 @Test 2 public void writeBean2XML() { 3 try { 4 fail("------------Bean->XML------------"); 5 fail(xstream.toXML(bean)); 6 fail("重命名后的XML"); 7 //类重命名 8 //xstream.alias("account", Student.class); 9 //xstream.alias("生日", Birthday.class); 10 //xstream.aliasField("生日", Student.class, "birthday"); 11 //xstream.aliasField("生日", Birthday.class, "birthday"); 12 //fail(xstream.toXML(bean)); 13 //属性重命名 14 xstream.aliasField("邮件", Student.class, "email"); 15 //包重命名 16 xstream.aliasPackage("hoo", "com.hoo.entity"); 17 fail(xstream.toXML(bean)); 18 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 }
看结果中的第一份xml内容,是没有经过然后修改或重命名的文档,按照原样输出。文档中的第二份文档的package经过重命名,email属性也经过重命名以及类名也可以进行重命名的。
运行后结果如下:
1 ------------Bean->XML------------ 2 <com.hoo.entity.Student> 3 <id>1</id> 4 <name>jack</name> 5 <email>jack@email.com</email> 6 <address>china</address> 7 <birthday> 8 <birthday>2010-11-22</birthday> 9 </birthday> 10 </com.hoo.entity.Student> 11 12 重命名后的XML 13 <hoo.Student> 14 <id>1</id> 15 <name>jack</name> 16 <邮件>jack@email.com</邮件> 17 <address>china</address> 18 <birthday> 19 <birthday>2010-11-22</birthday> 20 </birthday> 21 </hoo.Student>
2、 将List集合转换成xml文档
1 @Test 2 public void writeList2XML() { 3 try { 4 //修改元素名称 5 xstream.alias("beans", ListBean.class); 6 xstream.alias("student", Student.class); 7 fail("----------List-->XML----------"); 8 ListBean listBean = new ListBean(); 9 listBean.setName("this is a List Collection"); 10 List<Object> list = new ArrayList<Object>(); 11 list.add(bean); 12 list.add(bean);//引用bean 13 //list.add(listBean);//引用listBean,父元素 14 bean = new Student(); 15 bean.setAddress("china"); 16 bean.setEmail("tom@125.com"); 17 bean.setId(2); 18 bean.setName("tom"); 19 Birthday day = new Birthday("2010-11-22"); 20 bean.setBirthday(day); 21 list.add(bean); 22 listBean.setList(list); 23 //将ListBean中的集合设置空元素,即不显示集合元素标签 24 //xstream.addImplicitCollection(ListBean.class, "list"); 25 //设置reference模型 26 //xstream.setMode(XStream.NO_REFERENCES);//不引用 27 xstream.setMode(XStream.ID_REFERENCES);//id引用 28 //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用 29 30 //将name设置为父类(Student)的元素的属性 31 xstream.useAttributeFor(Student.class, "name"); 32 xstream.useAttributeFor(Birthday.class, "birthday"); 33 //修改属性的name 34 xstream.aliasAttribute("姓名", "name"); 35 xstream.aliasField("生日", Birthday.class, "birthday"); 36 fail(xstream.toXML(listBean)); 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 }
上面的代码运行后,结果如下:
1 ----------List-->XML---------- 2 3 <beans id="1"> 4 <name>this is a List Collection</name> 5 <list id="2"> 6 <student id="3" 姓名="jack"> 7 <id>1</id> 8 <email>jack@email.com</email> 9 <address>china</address> 10 <birthday id="4" 生日="2010-11-22"/> 11 </student> 12 <student reference="3"/> 13 <student id="5" 姓名="tom"> 14 <id>2</id> 15 <email>tom@125.com</email> 16 <address>china</address> 17 <birthday id="6" 生日="2010-11-22"/> 18 </student> 19 </list> 20 </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的代码
1 package com.hoo.entity; 2 3 import java.util.Arrays; 4 import java.util.Calendar; 5 import java.util.GregorianCalendar; 6 import java.util.List; 7 8 import com.thoughtworks.xstream.annotations.XStreamAlias; 9 import com.thoughtworks.xstream.annotations.XStreamAsAttribute; 10 import com.thoughtworks.xstream.annotations.XStreamConverter; 11 import com.thoughtworks.xstream.annotations.XStreamImplicit; 12 import com.thoughtworks.xstream.annotations.XStreamOmitField; 13 14 @XStreamAlias("class") 15 public class Classes { 16 /* 17 * 设置属性显示 18 */ 19 @XStreamAsAttribute 20 @XStreamAlias("名称") 21 private String name; 22 23 /* 24 * 忽略 25 */ 26 @XStreamOmitField 27 private int number; 28 29 @XStreamImplicit(itemFieldName = "Students") 30 private List<Student> students; 31 32 @SuppressWarnings("unused") 33 @XStreamConverter(SingleValueCalendarConverter.class) 34 private Calendar created = new GregorianCalendar(); 35 36 public Classes(){} 37 38 public Classes(String name, Student... stu) { 39 this.name = name; 40 this.students = Arrays.asList(stu); 41 } 42 //getter、setter省略 43 } 44 45 SingleValueCalendarConverter.java这个是一个类型转换器 46 package com.hoo.entity; 47 48 import java.util.Calendar; 49 import java.util.Date; 50 import java.util.GregorianCalendar; 51 52 import com.thoughtworks.xstream.converters.Converter; 53 import com.thoughtworks.xstream.converters.MarshallingContext; 54 import com.thoughtworks.xstream.converters.UnmarshallingContext; 55 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 56 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 57 58 public class SingleValueCalendarConverter implements Converter { 59 public void marshal(Object source, HierarchicalStreamWriter writer, 60 MarshallingContext context) { 61 Calendar calendar = (Calendar) source; 62 writer.setValue(String.valueOf(calendar.getTime().getTime())); 63 } 64 65 public Object unmarshal(HierarchicalStreamReader reader, 66 UnmarshallingContext context) { 67 GregorianCalendar calendar = new GregorianCalendar(); 68 calendar.setTime(new Date(Long.parseLong(reader.getValue()))); 69 return calendar; 70 } 71 72 @SuppressWarnings("unchecked") 73 public boolean canConvert(Class type) { 74 return type.equals(GregorianCalendar.class); 75 } 76 }
再看看测试用例代码
1 @Test 2 public void writeList2XML4Annotation() { 3 try { 4 failRed("---------annotation Bean --> XML---------"); 5 Student stu = new Student(); 6 stu.setName("jack"); 7 Classes c = new Classes("一班", bean, stu); 8 c.setNumber(2); 9 //对指定的类使用Annotation 10 //xstream.processAnnotations(Classes.class); 11 //启用Annotation 12 //xstream.autodetectAnnotations(true); 13 xstream.alias("student", Student.class); 14 fail(xstream.toXML(c)); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 }
当启用annotation或是对某个特定的类启用annotation时,上面的classes这个类才有效果。如果不启用annotation,运行后结果如下:
1 ---------annotation Bean --> XML--------- 2 3 <com.hoo.entity.Classes> 4 <name>一班</name> 5 <number>2</number> 6 <students class="java.util.Arrays$ArrayList"> 7 <a class="student-array"> 8 <student> 9 <id>1</id> 10 <name>jack</name> 11 <email>jack@email.com</email> 12 <address>china</address> 13 <birthday> 14 <birthday>2010-11-22</birthday> 15 </birthday> 16 </student> 17 <student> 18 <id>0</id> 19 <name>jack</name> 20 </student> 21 </a> 22 </students> 23 <created> 24 <time>1303292056718</time> 25 <timezone>Asia/Shanghai</timezone> 26 </created> 27 </com.hoo.entity.Classes>
当启用annotation后xstream.processAnnotations(Classes.class),结果如下:
1 ---------annotation Bean --> XML--------- 2 3 <class 名称="一班"> 4 <Students> 5 <id>1</id> 6 <name>jack</name> 7 <email>jack@email.com</email> 8 <address>china</address> 9 <birthday> 10 <birthday>2010-11-22</birthday> 11 </birthday> 12 </Students> 13 <Students> 14 <id>0</id> 15 <name>jack</name> 16 </Students> 17 <created>1303292242937</created> 18 </class>
4、 Map集合转换xml文档
1 @Test 2 public void writeMap2XML() { 3 try { 4 failRed("---------Map --> XML---------"); 5 Map<String, Student> map = new HashMap<String, Student>(); 6 map.put("No.1", bean);//put 7 bean = new Student(); 8 bean.setAddress("china"); 9 bean.setEmail("tom@125.com"); 10 bean.setId(2); 11 bean.setName("tom"); 12 Birthday day = new Birthday("2010-11-22"); 13 bean.setBirthday(day); 14 map.put("No.2", bean);//put 15 bean = new Student(); 16 bean.setName("jack"); 17 map.put("No.3", bean);//put 18 xstream.alias("student", Student.class); 19 xstream.alias("key", String.class); 20 xstream.useAttributeFor(Student.class, "id"); 21 xstream.useAttributeFor("birthday", String.class); 22 fail(xstream.toXML(map)); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 }
运行后结果如下:
1 ---------Map --> XML--------- 2 <map> 3 <entry> 4 <key>No.3</key> 5 <student id="0"> 6 <name>jack</name> 7 </student> 8 </entry> 9 <entry> 10 <key>No.1</key> 11 <student id="1"> 12 <name>jack</name> 13 <email>jack@email.com</email> 14 <address>china</address> 15 <birthday birthday="2010-11-22"/> 16 </student> 17 </entry> 18 <entry> 19 <key>No.2</key> 20 <student id="2"> 21 <name>tom</name> 22 <email>tom@125.com</email> 23 <address>china</address> 24 <birthday birthday="2010-11-22"/> 25 </student> 26 </entry> 27 </map>
5、 用OutStream输出流写XML
1 @Test 2 public void writeXML4OutStream() { 3 try { 4 out = xstream.createObjectOutputStream(System.out); 5 Student stu = new Student(); 6 stu.setName("jack"); 7 Classes c = new Classes("一班", bean, stu); 8 c.setNumber(2); 9 failRed("---------ObjectOutputStream # JavaObject--> XML---------"); 10 out.writeObject(stu); 11 out.writeObject(new Birthday("2010-05-33")); 12 out.write(22);//byte 13 out.writeBoolean(true); 14 out.writeFloat(22.f); 15 out.writeUTF("hello"); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19 }
使用输出流后,可以通过流对象完成xml的构建,即使没有JavaBean对象,你可以用流来构建一个复杂的xml文档,运行后结果如下:
1 ---------ObjectOutputStream # JavaObject--> XML--------- 2 <object-stream> 3 <com.hoo.entity.Student> 4 <id>0</id> 5 <name>jack</name> 6 </com.hoo.entity.Student> 7 <com.hoo.entity.Birthday> 8 <birthday>2010-05-33</birthday> 9 </com.hoo.entity.Birthday> 10 <byte>22</byte> 11 <boolean>true</boolean> 12 <float>22.0</float> 13 <string>hello</string> 14 </object-stream>
三、XML内容转换Java对象
1、 用InputStream将XML文档转换成java对象
1 @Test 2 public void readXML4InputStream() { 3 try { 4 String s = "<object-stream><com.hoo.entity.Student><id>0</id><name>jack</name>" + 5 "</com.hoo.entity.Student><com.hoo.entity.Birthday><birthday>2010-05-33</birthday>" + 6 "</com.hoo.entity.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" + 7 "<string>hello</string></object-stream>"; 8 failRed("---------ObjectInputStream## XML --> javaObject---------"); 9 StringReader reader = new StringReader(s); 10 in = xstream.createObjectInputStream(reader); 11 Student stu = (Student) in.readObject(); 12 Birthday b = (Birthday) in.readObject(); 13 byte i = in.readByte(); 14 boolean bo = in.readBoolean(); 15 float f = in.readFloat(); 16 String str = in.readUTF(); 17 System.out.println(stu); 18 System.out.println(b); 19 System.out.println(i); 20 System.out.println(bo); 21 System.out.println(f); 22 System.out.println(str); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 }
读取后,转换的Java对象,结果如下:
1 ---------ObjectInputStream## XML --> javaObject--------- 2 jack#0#null#null#null 3 2010-05-33 4 22 5 true 6 22.0 7 hello
2、 将xml文档转换成Java对象
1 @Test 2 public void readXml2Object() { 3 try { 4 failRed("-----------Xml >>> Bean--------------"); 5 Student stu = (Student) xstream.fromXML(xstream.toXML(bean)); 6 fail(stu.toString()); 7 8 List<Student> list = new ArrayList<Student>(); 9 list.add(bean);//add 10 Map<String, Student> map = new HashMap<String, Student>(); 11 map.put("No.1", bean);//put 12 bean = new Student(); 13 bean.setAddress("china"); 14 bean.setEmail("tom@125.com"); 15 bean.setId(2); 16 bean.setName("tom"); 17 Birthday day = new Birthday("2010-11-22"); 18 bean.setBirthday(day); 19 list.add(bean);//add 20 map.put("No.2", bean);//put 21 bean = new Student(); 22 bean.setName("jack"); 23 list.add(bean);//add 24 map.put("No.3", bean);//put 25 failRed("==========XML >>> List==========="); 26 List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list)); 27 fail("size:" + studetns.size());//3 28 for (Student s : studetns) { 29 fail(s.toString()); 30 } 31 32 failRed("==========XML >>> Map==========="); 33 Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map)); 34 fail("size:" + maps.size());//3 35 Set<String> key = maps.keySet(); 36 Iterator<String> iter = key.iterator(); 37 while (iter.hasNext()) { 38 String k = iter.next(); 39 fail(k + ":" + map.get(k)); 40 } 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 }
运行后结果如下:
-----------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
四、XStream对JSON的支持
xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar
1、 用JettisonMappedXmlDriver完成Java对象到JSON的转换
1 /** 2 * <b>function:</b>XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON 3 * 需要添加jettison jar 4 * @createDate Nov 27, 2010 1:23:18 PM 5 */ 6 @Test 7 public void writeEntity2JETTSON() { 8 failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString========="); 9 xstream = new XStream(new JettisonMappedXmlDriver()); 10 xstream.setMode(XStream.NO_REFERENCES); 11 xstream.alias("student", Student.class); 12 fail(xstream.toXML(bean)); 13 }
运行后结果如下:
1 =======JettisonMappedXmlDriver===JavaObject >>>> JaonString========= 2 {"student":{"id":1,"name":"jack","email":"jack@email.com","address":"china","birthday":[{},"2010-11-22"]}}
1 /** 2 * <b>function:</b>用XStream结合JsonHierarchicalStreamDriver驱动 3 * 转换java对象为JSON字符串 4 * @createDate Nov 27, 2010 1:16:46 PM 5 */ 6 @Test 7 public void writeEntiry2JSON() { 8 failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); 9 xstream = new XStream(new JsonHierarchicalStreamDriver()); 10 //xstream.setMode(XStream.NO_REFERENCES); 11 xstream.alias("student", Student.class); 12 failRed("-------Object >>>> JSON---------"); 13 fail(xstream.toXML(bean)); 14 //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); 15 //删除根节点 16 xstream = new XStream(new JsonHierarchicalStreamDriver() { 17 public HierarchicalStreamWriter createWriter(Writer out) { 18 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); 19 } 20 }); 21 //xstream.setMode(XStream.NO_REFERENCES); 22 xstream.alias("student", Student.class); 23 fail(xstream.toXML(bean)); 24 }
运行后结果如下:
1 ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= 2 -------Object >>>> JSON--------- 3 {"student": { 4 "id": 1, 5 "name": "jack", 6 "email": "jack@email.com", 7 "address": "china", 8 "birthday": { 9 "birthday": "2010-11-22" 10 } 11 }} 12 { 13 "id": 1, 14 "name": "jack", 15 "email": "jack@email.com", 16 "address": "china", 17 "birthday": { 18 "birthday": "2010-11-22" 19 } 20 }
使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,你可以重写createWriter方法,删掉根节点。
看上面的结果,一个是默认带根节点的JSON对象,它只是将类名作为一个属性,将对象作为该属性的一个值。而另一个没有带根属性的JSON就是通过重写createWriter方法完成的。
3、 将List集合转换成JSON字符串
1 @Test 2 public void writeList2JSON() { 3 failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); 4 JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver(); 5 xstream = new XStream(driver); 6 //xstream = new XStream(new JettisonMappedXmlDriver());//转换错误 7 //xstream.setMode(XStream.NO_REFERENCES); 8 xstream.alias("student", Student.class); 9 List<Student> list = new ArrayList<Student>(); 10 list.add(bean);//add 11 bean = new Student(); 12 bean.setAddress("china"); 13 bean.setEmail("tom@125.com"); 14 bean.setId(2); 15 bean.setName("tom"); 16 Birthday day = new Birthday("2010-11-22"); 17 bean.setBirthday(day); 18 list.add(bean);//add 19 bean = new Student(); 20 bean.setName("jack"); 21 list.add(bean);//add 22 fail(xstream.toXML(list)); 23 //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); 24 //删除根节点 25 xstream = new XStream(new JsonHierarchicalStreamDriver() { 26 public HierarchicalStreamWriter createWriter(Writer out) { 27 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); 28 } 29 }); 30 xstream.alias("student", Student.class); 31 fail(xstream.toXML(list)); 32 }
运行后结果如下:
1 ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========= 2 ##{"list": [ 3 { 4 "id": 1, 5 "name": "jack", 6 "email": "jack@email.com", 7 "address": "china", 8 "birthday": { 9 "birthday": "2010-11-22" 10 } 11 }, 12 { 13 "id": 2, 14 "name": "tom", 15 "email": "tom@125.com", 16 "address": "china", 17 "birthday": { 18 "birthday": "2010-11-22" 19 } 20 }, 21 { 22 "id": 0, 23 "name": "jack" 24 } 25 ]} 26 #[ 27 { 28 "id": 1, 29 "name": "jack", 30 "email": "jack@email.com", 31 "address": "china", 32 "birthday": { 33 "birthday": "2010-11-22" 34 } 35 }, 36 { 37 "id": 2, 38 "name": "tom", 39 "email": "tom@125.com", 40 "address": "china", 41 "birthday": { 42 "birthday": "2010-11-22" 43 } 44 }, 45 { 46 "id": 0, 47 "name": "jack" 48 } 49 ]
上面的list1是使用JsonHierarchicalStreamDriver 转换的,当然你也可以使用JettisonMappedXmlDriver驱动进行转换;用JettisonMappedXmlDriver转换后,你会发现格式不同而且没有根属性。
4、 Map转换json
1 @Test 2 public void writeMap2JSON() { 3 failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString========="); 4 xstream = new XStream(new JsonHierarchicalStreamDriver()); 5 //xstream = new XStream(new JettisonMappedXmlDriver()); 6 xstream.alias("student", Student.class); 7 Map<String, Student> map = new HashMap<String, Student>(); 8 map.put("No.1", bean);//put 9 bean = new Student(); 10 bean.setAddress("china"); 11 bean.setEmail("tom@125.com"); 12 bean.setId(2); 13 bean.setName("tom"); 14 bean.setBirthday(new Birthday("2010-11-21")); 15 map.put("No.2", bean);//put 16 bean = new Student(); 17 bean.setName("jack"); 18 map.put("No.3", bean);//put 19 fail(xstream.toXML(map)); 20 //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); 21 //删除根节点 22 xstream = new XStream(new JsonHierarchicalStreamDriver() { 23 public HierarchicalStreamWriter createWriter(Writer out) { 24 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); 25 } 26 }); 27 xstream.alias("student", Student.class); 28 fail(xstream.toXML(map)); 29 }
运行后结果如下:
1 ======JsonHierarchicalStreamDriver==== Map >>>> JaonString========= 2 {"map": [ 3 [ 4 "No.3", 5 { 6 "id": 0, 7 "name": "jack" 8 } 9 ], 10 [ 11 "No.1", 12 { 13 "id": 1, 14 "name": "jack", 15 "email": "jack@email.com", 16 "address": "china", 17 "birthday": { 18 "birthday": "2010-11-22" 19 } 20 } 21 ], 22 [ 23 "No.2", 24 { 25 "id": 2, 26 "name": "tom", 27 "email": "tom@125.com", 28 "address": "china", 29 "birthday": { 30 "birthday": "2010-11-21" 31 } 32 } 33 ] 34 ]} 35 [ 36 [ 37 "No.3", 38 { 39 "id": 0, 40 "name": "jack" 41 } 42 ], 43 [ 44 "No.1", 45 { 46 "id": 1, 47 "name": "jack", 48 "email": "jack@email.com", 49 "address": "china", 50 "birthday": { 51 "birthday": "2010-11-22" 52 } 53 } 54 ], 55 [ 56 "No.2", 57 { 58 "id": 2, 59 "name": "tom", 60 "email": "tom@125.com", 61 "address": "china", 62 "birthday": { 63 "birthday": "2010-11-21" 64 } 65 } 66 ] 67 ]
5、 将JSON转换java对象
1 /** 2 * <b>function:</b>JsonHierarchicalStreamDriver可以将简单的json字符串转换成java对象,list、map转换不成功; 3 * JsonHierarchicalStreamDriver读取JSON字符串到java对象出错 4 * @throws JSONException 5 */ 6 @Test 7 public void readJSON2Object() throws JSONException { 8 String json = "{\"student\": {" + 9 "\"id\": 1," + 10 "\"name\": \"haha\"," + 11 "\"email\": \"email\"," + 12 "\"address\": \"address\"," + 13 "\"birthday\": {" + 14 "\"birthday\": \"2010-11-22\"" + 15 "}" + 16 "}}"; 17 //JsonHierarchicalStreamDriver读取JSON字符串到java对象出错,但JettisonMappedXmlDriver可以 18 xstream = new XStream(new JettisonMappedXmlDriver()); 19 xstream.alias("student", Student.class); 20 fail(xstream.fromXML(json).toString()); 21 //JettisonMappedXmlDriver转换List集合出错,但JsonHierarchicalStreamDriver可以转换正确 22 //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"]}} 23 24 json = "{\"list\": [{" + 25 "\"id\": 1," + 26 "\"name\": \"haha\"," + 27 "\"email\": \"email\"," + 28 "\"address\": \"address\"," + 29 "\"birthday\": {" + 30 "\"birthday\": \"2010-11-22\"" + 31 "}" + 32 "},{" + 33 "\"id\": 2," + 34 "\"name\": \"tom\"," + 35 "\"email\": \"tom@125.com\"," + 36 "\"address\": \"china\"," + 37 "\"birthday\": {" + 38 "\"birthday\": \"2010-11-22\"" + 39 "}" + 40 "}]}"; 41 System.out.println(json);//用js转换成功 42 List list = (List) xstream.fromXML(json); 43 System.out.println(list.size());//0好像转换失败 44 }
运行后结果如下:
1 haha#1#address#2010-11-22#email 2 {"list": [{"id": 1,"name": "haha","email": "email","address": "address","birthday": {"birthday": "2010-11-22"}}, 3 {"id": 2,"name": "tom","email": "tom@125.com","address": "china","birthday": {"birthday": "2010-11-22"}}]} 4 0
JSON到Java的转换是fromXML方法。
标签:
原文地址:http://www.cnblogs.com/angleBlue/p/4801477.html