xStream完美转换XML、JSON
xStream完美转换XML、JSON
xStream框架
xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;
前面有介绍过json-lib这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html
以及Jackson这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
它 们都完美支持JSON,但是对xml的支持还不是很好。一定程度上限制了对Java对象的描述,不能让xml完全体现到对Java对象的描述。这里将会介 绍xStream对JSON、XML的完美支持。xStream不仅对XML的转换非常友好,而且提供annotation注解,可以在JavaBean 中完成对xml节点、属性的描述。以及对JSON也支持,只需要提供相关的JSONDriver就可以完成转换。
一、准备工作
1、 下载jar包、及官方资源
xStream的jar下载地址:
官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html
添加xstream-1.3.1.jar文件到工程中,就可以开始下面的工作;需要的jar如下:
2、 测试用例代码
1 package com.hoo.test; 2 3 4 5 import java.io.IOException; 6 7 import java.io.ObjectInputStream; 8 9 import java.io.ObjectOutputStream; 10 11 import java.io.StringReader; 12 13 import java.io.Writer; 14 15 import java.util.ArrayList; 16 17 import java.util.HashMap; 18 19 import java.util.Iterator; 20 21 import java.util.List; 22 23 import java.util.Map; 24 25 import java.util.Set; 26 27 import org.codehaus.jettison.json.JSONException; 28 29 import org.junit.After; 30 31 import org.junit.Before; 32 33 import org.junit.Test; 34 35 import com.hoo.entity.Birthday; 36 37 import com.hoo.entity.Classes; 38 39 import com.hoo.entity.ListBean; 40 41 import com.hoo.entity.Student; 42 43 import com.thoughtworks.xstream.XStream; 44 45 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 46 47 import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; 48 49 import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; 50 51 import com.thoughtworks.xstream.io.json.JsonWriter; 52 53 54 55 /** 56 57 * <b>function:</b>Java对象和XML字符串的相互转换 58 59 * jar-lib-version: xstream-1.3.1 60 61 * @author hoojo 62 63 * @createDate Nov 27, 2010 12:15:15 PM 64 65 * @file XStreamTest.java 66 67 * @package com.hoo.test 68 69 * @project WebHttpUtils 70 71 * @blog http://blog.csdn.net/IBM_hoojo 72 73 * @email hoojo_@126.com 74 75 * @version 1.0 76 77 */ 78 79 @SuppressWarnings("unchecked") 80 81 public class XStreamTest { 82 83 84 85 private XStream xstream = null; 86 87 private ObjectOutputStream out = null; 88 89 private ObjectInputStream in = null; 90 91 92 93 private Student bean = null; 94 95 96 97 /** 98 99 * <b>function:</b>初始化资源准备 100 101 * @author hoojo 102 103 * @createDate Nov 27, 2010 12:16:28 PM 104 105 */ 106 107 @Before 108 109 public void init() { 110 111 try { 112 113 xstream = new XStream(); 114 115 //xstream = new XStream(new DomDriver()); // 需要xpp3 jar 116 117 } catch (Exception e) { 118 119 e.printStackTrace(); 120 121 } 122 123 bean = new Student(); 124 125 bean.setAddress("china"); 126 127 bean.setEmail("jack@email.com"); 128 129 bean.setId(1); 130 131 bean.setName("jack"); 132 133 Birthday day = new Birthday(); 134 135 day.setBirthday("2010-11-22"); 136 137 bean.setBirthday(day); 138 139 } 140 141 142 143 /** 144 145 * <b>function:</b>释放对象资源 146 147 * @author hoojo 148 149 * @createDate Nov 27, 2010 12:16:38 PM 150 151 */ 152 153 @After 154 155 public void destory() { 156 157 xstream = null; 158 159 bean = null; 160 161 try { 162 163 if (out != null) { 164 165 out.flush(); 166 167 out.close(); 168 169 } 170 171 if (in != null) { 172 173 in.close(); 174 175 } 176 177 } catch (IOException e) { 178 179 e.printStackTrace(); 180 181 } 182 183 System.gc(); 184 185 } 186 187 188 189 public final void fail(String string) { 190 191 System.out.println(string); 192 193 } 194 195 196 197 public final void failRed(String string) { 198 199 System.err.println(string); 200 201 } 202 203 }
通过XStream对象的toXML方法就可以完成Java对象到XML的转换,toXML方法还有2个相同签名的方法,需要传递一个流。然后通过流来完成xml信息的输出。
3、 需要的JavaBean
1 package com.hoo.entity; 2 3 4 5 public class Student { 6 7 private int id; 8 9 private String name; 10 11 private String email; 12 13 private String address; 14 15 private Birthday birthday; 16 17 //getter、setter 18 19 public String toString() { 20 21 return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email; 22 23 } 24 25 }
二、Java转换成XML
1、 JavaBean转换XM
1 /** 2 3 * <b>function:</b>Java对象转换成XML字符串 4 5 * @author hoojo 6 7 * @createDate Nov 27, 2010 12:19:01 PM 8 9 */ 10 11 @Test 12 13 public void writeBean2XML() { 14 15 try { 16 17 fail("------------Bean->XML------------"); 18 19 fail(xstream.toXML(bean)); 20 21 fail("重命名后的XML"); 22 23 //类重命名 24 25 //xstream.alias("account", Student.class); 26 27 //xstream.alias("生日", Birthday.class); 28 29 //xstream.aliasField("生日", Student.class, "birthday"); 30 31 //xstream.aliasField("生日", Birthday.class, "birthday"); 32 33 //fail(xstream.toXML(bean)); 34 35 //属性重命名 36 37 xstream.aliasField("邮件", Student.class, "email"); 38 39 //包重命名 40 41 xstream.aliasPackage("hoo", "com.hoo.entity"); 42 43 fail(xstream.toXML(bean)); 44 45 } catch (Exception e) { 46 47 e.printStackTrace(); 48 49 } 50 51 }
看结果中的第一份xml内容,是没有经过然后修改或重命名的文档,按照原样输出。文档中的第二份文档的package经过重命名,email属性也经过重命名以及类名也可以进行重命名的。
运行后结果如下:
1 ------------Bean->XML------------ 2 3 <com.hoo.entity.Student> 4 5 <id>1</id> 6 7 <name>jack</name> 8 9 <email>jack@email.com</email> 10 11 <address>china</address> 12 13 <birthday> 14 15 <birthday>2010-11-22</birthday> 16 17 </birthday> 18 19 </com.hoo.entity.Student> 20 21 重命名后的XML 22 23 <hoo.Student> 24 25 <id>1</id> 26 27 <name>jack</name> 28 29 <邮件>jack@email.com</邮件> 30 31 <address>china</address> 32 33 <birthday> 34 35 <birthday>2010-11-22</birthday> 36 37 </birthday> 38 39 </hoo.Student>
2、 将List集合转换成xml文档
1 /** 2 3 * <b>function:</b>将Java的List集合转换成XML对象 4 5 * @author hoojo 6 7 * @createDate Nov 27, 2010 12:20:07 PM 8 9 */ 10 11 @Test 12 13 public void writeList2XML() { 14 15 try { 16 17 //修改元素名称 18 19 xstream.alias("beans", ListBean.class); 20 21 xstream.alias("student", Student.class); 22 23 fail("----------List-->XML----------"); 24 25 ListBean listBean = new ListBean(); 26 27 listBean.setName("this is a List Collection"); 28 29 30 31 List<Object> list = new ArrayList<Object>(); 32 33 list.add(bean); 34 35 list.add(bean);//引用bean 36 37 //list.add(listBean);//引用listBean,父元素 38 39 40 41 bean = new Student(); 42 43 bean.setAddress("china"); 44 45 bean.setEmail("tom@125.com"); 46 47 bean.setId(2); 48 49 bean.setName("tom"); 50 51 Birthday day = new Birthday("2010-11-22"); 52 53 bean.setBirthday(day); 54 55 56 57 list.add(bean); 58 59 listBean.setList(list); 60 61 62 63 //将ListBean中的集合设置空元素,即不显示集合元素标签 64 65 //xstream.addImplicitCollection(ListBean.class, "list"); 66 67 68 69 //设置reference模型 70 71 //xstream.setMode(XStream.NO_REFERENCES);//不引用 72 73 xstream.setMode(XStream.ID_REFERENCES);//id引用 74 75 //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用 76 77 78 79 //将name设置为父类(Student)的元素的属性 80 81 xstream.useAttributeFor(Student.class, "name"); 82 83 xstream.useAttributeFor(Birthday.class, "birthday"); 84 85 //修改属性的name 86 87 xstream.aliasAttribute("姓名", "name"); 88 89 xstream.aliasField("生日", Birthday.class, "birthday"); 90 91 92 93 fail(xstream.toXML(listBean)); 94 95 } catch (Exception e) { 96 97 e.printStackTrace(); 98 99 } 100 101 }
上面的代码运行后,结果如下:
1 ----------List-->XML---------- 2 3 <beans id="1"> 4 5 <name>this is a List Collection</name> 6 7 <list id="2"> 8 9 <student id="3" 姓名="jack"> 10 11 <id>1</id> 12 13 <email>jack@email.com</email> 14 15 <address>china</address> 16 17 <birthday id="4" 生日="2010-11-22"/> 18 19 </student> 20 21 <student reference="3"/> 22 23 <student id="5" 姓名="tom"> 24 25 <id>2</id> 26 27 <email>tom@125.com</email> 28 29 <address>china</address> 30 31 <birthday id="6" 生日="2010-11-22"/> 32 33 </student> 34 35 </list> 36 37 </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 4 5 import java.util.Arrays; 6 7 import java.util.Calendar; 8 9 import java.util.GregorianCalendar; 10 11 import java.util.List; 12 13 import com.thoughtworks.xstream.annotations.XStreamAlias; 14 15 import com.thoughtworks.xstream.annotations.XStreamAsAttribute; 16 17 import com.thoughtworks.xstream.annotations.XStreamConverter; 18 19 import com.thoughtworks.xstream.annotations.XStreamImplicit; 20 21 import com.thoughtworks.xstream.annotations.XStreamOmitField; 22 23 24 25 @XStreamAlias("class") 26 27 public class Classes { 28 29 30 31 /* 32 33 * 设置属性显示 34 35 */ 36 37 @XStreamAsAttribute 38 39 @XStreamAlias("名称") 40 41 private String name; 42 43 44 45 /* 46 47 * 忽略 48 49 */ 50 51 @XStreamOmitField 52 53 private int number; 54 55 56 57 @XStreamImplicit(itemFieldName = "Students") 58 59 private List<Student> students; 60 61 62 63 @SuppressWarnings("unused") 64 65 @XStreamConverter(SingleValueCalendarConverter.class) 66 67 private Calendar created = new GregorianCalendar(); 68 69 70 71 72 73 public Classes(){} 74 75 public Classes(String name, Student... stu) { 76 77 this.name = name; 78 79 this.students = Arrays.asList(stu); 80 81 } 82 83 //getter、setter 84 85 }
SingleValueCalendarConverter.java这个是一个类型转换器
1 package com.hoo.entity; 2 3 4 5 import java.util.Calendar; 6 7 import java.util.Date; 8 9 import java.util.GregorianCalendar; 10 11 import com.thoughtworks.xstream.converters.Converter; 12 13 import com.thoughtworks.xstream.converters.MarshallingContext; 14 15 import com.thoughtworks.xstream.converters.UnmarshallingContext; 16 17 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 18 19 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 20 21 22 23 public class SingleValueCalendarConverter implements Converter { 24 25 public void marshal(Object source, HierarchicalStreamWriter writer, 26 27 MarshallingContext context) { 28 29 Calendar calendar = (Calendar) source; 30 31 writer.setValue(String.valueOf(calendar.getTime().getTime())); 32 33 } 34 35 36 37 public Object unmarshal(HierarchicalStreamReader reader, 38 39 UnmarshallingContext context) { 40 41 GregorianCalendar calendar = new GregorianCalendar(); 42 43 calendar.setTime(new Date(Long.parseLong(reader.getValue()))); 44 45 return calendar; 46 47 } 48 49 50 51 @SuppressWarnings("unchecked") 52 53 public boolean canConvert(Class type) { 54 55 return type.equals(GregorianCalendar.class); 56 57 } 58 59 }
再看看测试用例代码
1 @Test 2 3 public void writeList2XML4Annotation() { 4 5 try { 6 7 failRed("---------annotation Bean --> XML---------"); 8 9 Student stu = new Student(); 10 11 stu.setName("jack"); 12 13 Classes c = new Classes("一班", bean, stu); 14 15 c.setNumber(2); 16 17 //对指定的类使用Annotation 18 19 //xstream.processAnnotations(Classes.class); 20 21 //启用Annotation 22 23 //xstream.autodetectAnnotations(true); 24 25 xstream.alias("student", Student.class); 26 27 fail(xstream.toXML(c)); 28 29 } catch (Exception e) { 30 31 e.printStackTrace(); 32 33 } 34 35 }
当启用annotation或是对某个特定的类启用annotation时,上面的classes这个类才有效果。如果不启用annotation,运行后结果如下:
1 ---------annotation Bean --> XML--------- 2 3 <com.hoo.entity.Classes> 4 5 <name>一班</name> 6 7 <number>2</number> 8 9 <students class="java.util.Arrays$ArrayList"> 10 11 <a class="student-array"> 12 13 <student> 14 15 <id>1</id> 16 17 <name>jack</name> 18 19 <email>jack@email.com</email> 20 21 <address>china</address> 22 23 <birthday> 24 25 <birthday>2010-11-22</birthday> 26 27 </birthday> 28 29 </student> 30 31 <student> 32 33 <id>0</id> 34 35 <name>jack</name> 36 37 </student> 38 39 </a> 40 41 </students> 42 43 <created> 44 45 <time>1303292056718</time> 46 47 <timezone>Asia/Shanghai</timezone> 48 49 </created> 50 51 </com.hoo.entity.Classes>
当启用annotation后xstream.processAnnotations(Classes.class),结果如下:
1 ---------annotation Bean --> XML--------- 2 3 <class 名称="一班"> 4 5 <Students> 6 7 <id>1</id> 8 9 <name>jack</name> 10 11 <email>jack@email.com</email> 12 13 <address>china</address> 14 15 <birthday> 16 17 <birthday>2010-11-22</birthday> 18 19 </birthday> 20 21 </Students> 22 23 <Students> 24 25 <id>0</id> 26 27 <name>jack</name> 28 29 </Students> 30 31 <created>1303292242937</created> 32 33 </class>
4、 Map集合转换xml文档
1 /** 2 3 * <b>function:</b>Java Map集合转XML 4 5 * @author hoojo 6 7 * @createDate Nov 27, 2010 1:13:26 PM 8 9 */ 10 11 @Test 12 13 public void writeMap2XML() { 14 15 try { 16 17 failRed("---------Map --> XML---------"); 18 19 Map<String, Student> map = new HashMap<String, Student>(); 20 21 map.put("No.1", bean);//put 22 23 24 25 bean = new Student(); 26 27 bean.setAddress("china"); 28 29 bean.setEmail("tom@125.com"); 30 31 bean.setId(2); 32 33 bean.setName("tom"); 34 35 Birthday day = new Birthday("2010-11-22"); 36 37 bean.setBirthday(day); 38 39 map.put("No.2", bean);//put 40 41 42 43 bean = new Student(); 44 45 bean.setName("jack"); 46 47 map.put("No.3", bean);//put 48 49 50 51 xstream.alias("student", Student.class); 52 53 xstream.alias("key", String.class); 54 55 xstream.useAttributeFor(Student.class, "id"); 56 57 xstream.useAttributeFor("birthday", String.class); 58 59 fail(xstream.toXML(map)); 60 61 } catch (Exception e) { 62 63 e.printStackTrace(); 64 65 } 66 67 }
运行后结果如下:
1 ---------Map --> XML--------- 2 3 <map> 4 5 <entry> 6 7 <key>No.3</key> 8 9 <student id="0"> 10 11 <name>jack</name> 12 13 </student> 14 15 </entry> 16 17 <entry> 18 19 <key>No.1</key> 20 21 <student id="1"> 22 23 <name>jack</name> 24 25 <email>jack@email.com</email> 26 27 <address>china</address> 28 29 <birthday birthday="2010-11-22"/> 30 31 </student> 32 33 </entry> 34 35 <entry> 36 37 <key>No.2</key> 38 39 <student id="2"> 40 41 <name>tom</name> 42 43 <email>tom@125.com</email> 44 45 <address>china</address> 46 47 <birthday birthday="2010-11-22"/> 48 49 </student> 50 51 </entry> 52 53 </map>
5、 用OutStream输出流写XML
1 /** 2 3 * <b>function:</b>用OutStream输出流写XML 4 5 * @author hoojo 6 7 * @createDate Nov 27, 2010 1:13:48 PM 8 9 */ 10 11 @Test 12 13 public void writeXML4OutStream() { 14 15 try { 16 17 out = xstream.createObjectOutputStream(System.out); 18 19 Student stu = new Student(); 20 21 stu.setName("jack"); 22 23 Classes c = new Classes("一班", bean, stu); 24 25 c.setNumber(2); 26 27 failRed("---------ObjectOutputStream # JavaObject--> XML---------"); 28 29 out.writeObject(stu); 30 31 out.writeObject(new Birthday("2010-05-33")); 32 33 out.write(22);//byte 34 35 out.writeBoolean(true); 36 37 out.writeFloat(22.f); 38 39 out.writeUTF("hello"); 40 41 42 43 } catch (Exception e) { 44 45 e.printStackTrace(); 46 47 } 48 49 }
使用输出流后,可以通过流对象完成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对象
1 /** 2 3 * <b>function:</b>用InputStream将XML文档转换成java对象 4 5 * 需要额外的jar xpp3-main.jar 6 7 * @author hoojo 8 9 * @createDate Nov 27, 2010 1:14:52 PM 10 11 */ 12 13 @Test 14 15 public void readXML4InputStream() { 16 17 try { 18 19 String s = "<object-stream><com.hoo.entity.Student><id>0</id><name>jack</name>" + 20 21 "</com.hoo.entity.Student><com.hoo.entity.Birthday><birthday>2010-05-33</birthday>" + 22 23 "</com.hoo.entity.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" + 24 25 "<string>hello</string></object-stream>"; 26 27 failRed("---------ObjectInputStream## XML --> javaObject---------"); 28 29 StringReader reader = new StringReader(s); 30 31 in = xstream.createObjectInputStream(reader); 32 33 Student stu = (Student) in.readObject(); 34 35 Birthday b = (Birthday) in.readObject(); 36 37 byte i = in.readByte(); 38 39 boolean bo = in.readBoolean(); 40 41 float f = in.readFloat(); 42 43 String str = in.readUTF(); 44 45 System.out.println(stu); 46 47 System.out.println(b); 48 49 System.out.println(i); 50 51 System.out.println(bo); 52 53 System.out.println(f); 54 55 System.out.println(str); 56 57 } catch (Exception e) { 58 59 e.printStackTrace(); 60 61 } 62 63 }
读取后,转换的Java对象,结果如下:
1 ---------ObjectInputStream## XML --> javaObject--------- 2 3 jack#0#null#null#null 4 5 2010-05-33 6 7 22 8 9 true 10 11 22.0 12 13 hello
2、 将xml文档转换成Java对象
1 /** 2 3 * <b>function:</b>将XML字符串转换成Java对象 4 5 * @author hoojo 6 7 * @createDate Nov 27, 2010 2:39:06 PM 8 9 */ 10 11 @Test 12 13 public void readXml2Object() { 14 15 try { 16 17 failRed("-----------Xml >>> Bean--------------"); 18 19 Student stu = (Student) xstream.fromXML(xstream.toXML(bean)); 20 21 fail(stu.toString()); 22 23 24 25 List<Student> list = new ArrayList<Student>(); 26 27 list.add(bean);//add 28 29 30 31 Map<String, Student> map = new HashMap<String, Student>(); 32 33 map.put("No.1", bean);//put 34 35 36 37 bean = new Student(); 38 39 bean.setAddress("china"); 40 41 bean.setEmail("tom@125.com"); 42 43 bean.setId(2); 44 45 bean.setName("tom"); 46 47 Birthday day = new Birthday("2010-11-22"); 48 49 bean.setBirthday(day); 50 51 list.add(bean);//add 52 53 map.put("No.2", bean);//put 54 55 56 57 bean = new Student(); 58 59 bean.setName("jack"); 60 61 list.add(bean);//add 62 63 map.put("No.3", bean);//put 64 65 66 67 failRed("==========XML >>> List==========="); 68 69 List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list)); 70 71 fail("size:" + studetns.size());//3 72 73 for (Student s : studetns) { 74 75 fail(s.toString()); 76 77 } 78 79 80 81 failRed("==========XML >>> Map==========="); 82 83 Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map)); 84 85 fail("size:" + maps.size());//3 86 87 Set<String> key = maps.keySet(); 88 89 Iterator<String> iter = key.iterator(); 90 91 while (iter.hasNext()) { 92 93 String k = iter.next(); 94 95 fail(k + ":" + map.get(k)); 96 97 } 98 99 } catch (Exception e) { 100 101 e.printStackTrace(); 102 103 } 104 105 }
运行后结果如下:
1 -----------Xml >>> Bean-------------- 2 3 jack#1#china#2010-11-22#jack@email.com 4 5 ==========XML >>> List=========== 6 7 size:3 8 9 jack#1#china#2010-11-22#jack@email.com 10 11 tom#2#china#2010-11-22#tom@125.com 12 13 jack#0#null#null#null 14 15 ==========XML >>> Map=========== 16 17 size:3 18 19 No.3:jack#0#null#null#null 20 21 No.1:jack#1#china#2010-11-22#jack@email.com 22 23 No.2:tom#2#china#2010-11-22#tom@125.com
怎么样,成功的完成XML到JavaBean、List、Map的转换,更多对象转换还需要大家一一尝试。用法类似~这里就不一样赘述。
四、XStream对JSON的支持
xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar
1、 用JettisonMappedXmlDriver完成Java对象到JSON的转换
1 /** 2 3 * <b>function:</b>XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON 4 5 * 需要添加jettison jar 6 7 * @author hoojo 8 9 * @createDate Nov 27, 2010 1:23:18 PM 10 11 */ 12 13 @Test 14 15 public void writeEntity2JETTSON() { 16 17 failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString========="); 18 19 xstream = new XStream(new JettisonMappedXmlDriver()); 20 21 xstream.setMode(XStream.NO_REFERENCES); 22 23 xstream.alias("student", Student.class); 24 25 fail(xstream.toXML(bean)); 26 27 }
运行后结果如下:
=======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。
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": "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方法完成的。
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("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转换后,你会发现格式不同而且没有根属性。
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("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" } } ] ]
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":"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方法。
作者:hoojo
出处:
http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
blog:http://blog.csdn.net/IBM_hoojo
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。