nevergiveupzeng

导航

xStream转换XML、JSON

 
 

一. 简介

xStream可以很容易实现Java对象和xml文档互相转换, 可以修改某个特定的属性和节点名称,xStream提供annotation注解,

可以在JavaBean中完成对xml节点和属性的描述,并支持Json的转换,只需要提供相关的JSONDriver就能完成转换

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

 

 

二. 准备工作

1. 环境准备:

Jar文件下载地址:

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

代码结构图:

 

2. junit测试代码:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class XStreamTest {  
  2.     private XStream xstream;  
  3.     private ObjectOutputStream out;  
  4.     private ObjectInputStream in;  
  5.     private Student student;  
  6.   
  7.     /** 
  8.      * 初始化资源准备 
  9.      */  
  10.     @Before  
  11.     public void init() {  
  12.         try {  
  13.             xstream = new XStream(new DomDriver());  
  14.         } catch (Exception e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.         student = new Student();  
  18.         student.setAddress("china");  
  19.         student.setEmail("jack@email.com");  
  20.         student.setId(1);  
  21.         student.setName("jack");  
  22.         Birthday birthday = new Birthday();   
  23.         birthday.setBirthday("2010-11-22");  
  24.         student.setBirthday(birthday);  
  25.     }  
  26.   
  27.     /** 
  28.      * 释放对象资源 
  29.      */  
  30.     @After  
  31.     public void destory() {  
  32.         xstream = null;  
  33.         student = null;  
  34.         try {  
  35.             if (out != null) {  
  36.                 out.flush();  
  37.                 out.close();  
  38.             }  
  39.             if (in != null) {  
  40.                 in.close();  
  41.             }  
  42.         } catch (IOException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.         System.gc();  
  46.     }  
  47.       
  48.     /** 
  49.      * 打印字符串 
  50.      */  
  51.     public final void print(String string) {   
  52.         System.out.println(string);  
  53.     }  
  54.       
  55.     /** 
  56.      * 高亮字符串 
  57.      */  
  58.     public final void highLight(String string) {  
  59.         System.err.println(string);  
  60.     }  
  61.   
  62. }  

3. 所需实体类:

 

(1)Student:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class Student {  
  2.     private int id;  
  3.     private String name;  
  4.     private String email;  
  5.     private String address;  
  6.     private Birthday birthday;  
  7.     // getter and setter  
  8.     public String toString() {  
  9.         return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;  
  10.     }  
  11. }  

 

 

(2)Birthday

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class Birthday {  
  2.     private String birthday;  
  3.   
  4.     public Birthday() {  
  5.     }  
  6.       
  7.     public Birthday(String birthday) {  
  8.         this.birthday = birthday;  
  9.     }  
  10.   
  11.     public String getBirthday() {  
  12.         return birthday;  
  13.     }  
  14.   
  15.     public void setBirthday(String birthday) {  
  16.         this.birthday = birthday;  
  17.     }  
  18. }  

三 Java对象转为xml

1. 将JavaBean转成xml文档:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /**  
  2.      * Java对象转换成XML 
  3.      */  
  4.     @Test  
  5.     public void writeBean2XML() {  
  6.         try {  
  7.             highLight("====== Bean -> XML ======");  
  8.             print("<!-- 没有重命名的XML -->");  
  9.             print(xstream.toXML(student));  
  10.               
  11.             print("<!-- 重命名后的XML -->");  
  12.             // 类重命名  
  13.             xstream.alias("student", Student.class);  
  14.             xstream.alias("生日", Birthday.class);  
  15.             xstream.aliasField("生日", Student.class, "birthday");  
  16.             xstream.aliasField("生日", Birthday.class, "birthday");  
  17.   
  18.             // 属性重命名  
  19.             xstream.aliasField("邮件", Student.class, "email");  
  20.   
  21.             // 包重命名  
  22.             xstream.aliasPackage("zdp", "com.zdp.domain");  
  23.             print(xstream.toXML(student));  
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  

运行结果:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== Bean -XML ======  
  2. <!-- 没有重命名的XML -->  
  3. <com.zdp.domain.Student>  
  4.   <id>1</id>  
  5.   <name>jack</name>  
  6.   <email>jack@email.com</email>  
  7.   <address>china</address>  
  8.   <birthday>  
  9.     <birthday>2010-11-22</birthday>  
  10.   </birthday>  
  11. </com.zdp.domain.Student>  
  12. <!-- 重命名后的XML -->  
  13. <student>  
  14.   <id>1</id>  
  15.   <name>jack</name>  
  16.   <邮件>jack@email.com</邮件>  
  17.   <address>china</address>  
  18.   <生日>  
  19.     <生日>2010-11-22</生日>  
  20.   </生日>  
  21. </student>  

第一份文档是没有经过修改或重命名的文档, 按照原样输出。

第二份文档的类、属性、包都经过了重命名。

 

2. 将List集合转成xml文档:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将List集合转换成XML对象 
  3.      */  
  4.     @Test  
  5.     public void writeList2XML() {  
  6.         try {  
  7.             // 修改元素名称  
  8.             highLight("====== List --> XML ======");  
  9.             xstream.alias("beans", ListBean.class);  
  10.             xstream.alias("student", Student.class);  
  11.             ListBean listBean = new ListBean();  
  12.             listBean.setName("this is a List Collection");  
  13.   
  14.             List<Object> list = new ArrayList<Object>();  
  15.             // 引用javabean  
  16.             list.add(student);  
  17.             list.add(student);   
  18.             // list.add(listBean); 引用listBean,父元素  
  19.   
  20.             student = new Student();  
  21.             student.setAddress("china");  
  22.             student.setEmail("tom@125.com");  
  23.             student.setId(2);  
  24.             student.setName("tom");  
  25.             Birthday birthday = new Birthday("2010-11-22");   
  26.             student.setBirthday(birthday);  
  27.   
  28.             list.add(student);  
  29.             listBean.setList(list);  
  30.               
  31.             // 将ListBean中的集合设置空元素,即不显示集合元素标签  
  32.             // xstream.addImplicitCollection(ListBean.class, "list");  
  33.               
  34.             // 设置reference模型  
  35.             xstream.setMode(XStream.ID_REFERENCES); // id引用  
  36.             //xstream.setMode(XStream.NO_REFERENCES); // 不引用  
  37.             //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); // 绝对路径引用  
  38.               
  39.             // 将name设置为父类(Student)的元素的属性  
  40.             xstream.useAttributeFor(Student.class, "name");  
  41.             xstream.useAttributeFor(Birthday.class, "birthday");  
  42.               
  43.             // 修改属性的name  
  44.             xstream.aliasAttribute("姓名", "name");  
  45.             xstream.aliasField("生日", Birthday.class, "birthday");  
  46.   
  47.             print(xstream.toXML(listBean));  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.     }  

运行结果:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== List --XML ======  
  2. <beans id="1">  
  3.   <name>this is a List Collection</name>  
  4.   <list id="2">  
  5.     <student id="3" 姓名="jack">  
  6.       <id>1</id>  
  7.       <email>jack@email.com</email>  
  8.       <address>china</address>  
  9.       <birthday id="4" 生日="2010-11-22"/>  
  10.     </student>  
  11.     <student reference="3"/>  
  12.     <student id="5" 姓名="tom">  
  13.       <id>2</id>  
  14.       <email>tom@125.com</email>  
  15.       <address>china</address>  
  16.       <birthday id="6" 生日="2010-11-22"/>  
  17.     </student>  
  18.   </list>  
  19. </beans>  

3. 在JavaBean中添加Annotation注解进行重命名设置

(1)JavaBean代码:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. @XStreamAlias("class")  
  2. public class Classes {  
  3.   
  4.     @XStreamAsAttribute  
  5.     @XStreamAlias("名称")  
  6.     private String name;  
  7.   
  8.     @XStreamOmitField  
  9.     private int number;  
  10.   
  11.     @XStreamImplicit(itemFieldName = "Students")  
  12.     private List<Student> students;  
  13.   
  14.     @XStreamConverter(SingleValueCalendarConverter.class)  
  15.     private Calendar created = new GregorianCalendar();  
  16.   
  17.     public Classes() {  
  18.     }  
  19.   
  20.     public Classes(String name, Student... stu) {  
  21.         this.name = name;  
  22.         this.students = Arrays.asList(stu);  
  23.     }  
  24.   
  25.     public String getName() {  
  26.         return name;  
  27.     }  
  28.   
  29.     public void setName(String name) {  
  30.         this.name = name;  
  31.     }  
  32.   
  33.     public int getNumber() {  
  34.         return number;  
  35.     }  
  36.   
  37.     public void setNumber(int number) {  
  38.         this.number = number;  
  39.     }  
  40.   
  41.     public List<Student> getStudents() {  
  42.         return students;  
  43.     }  
  44.   
  45.     public void setStudents(List<Student> students) {  
  46.         this.students = students;  
  47.     }  
  48.   
  49.     public Calendar getCreated() {  
  50.         return created;  
  51.     }  
  52.   
  53.     public void setCreated(Calendar created) {  
  54.         this.created = created;  
  55.     }  
  56.       
  57. }  

 

(2)编写类型转换器:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class SingleValueCalendarConverter implements Converter {  
  2.     public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {  
  3.         Calendar calendar = (Calendar) source;  
  4.         writer.setValue(String.valueOf(calendar.getTime().getTime()));  
  5.     }  
  6.   
  7.     public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {  
  8.         GregorianCalendar calendar = new GregorianCalendar();  
  9.         calendar.setTime(new Date(Long.parseLong(reader.getValue())));  
  10.         return calendar;  
  11.     }  
  12.   
  13.     public boolean canConvert(Class type) {  
  14.         return type.equals(GregorianCalendar.class);  
  15.     }  
  16. }  

(3)测试代码:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 使用注解将List转为XML文档 
  3.      */  
  4.     @Test  
  5.     public void writeList2XML4Annotation() {  
  6.         try {  
  7.             highLight("====== annotation Bean --> XML ======");  
  8.             Student stu = new Student();  
  9.             stu.setName("jack");  
  10.             Classes c = new Classes("一班", student, stu);  
  11.             c.setNumber(2);  
  12.             xstream.alias("student", Student.class);  
  13.             print(xstream.toXML(c));  
  14.         } catch (Exception e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
运行结果:

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== annotation Bean --XML ======  
  2. <com.zdp.domain.Classes>  
  3.   <name>一班</name>  
  4.   <number>2</number>  
  5.   <students class="java.util.Arrays$ArrayList">  
  6.     <class="student-array">  
  7.       <student>  
  8.         <id>1</id>  
  9.         <name>jack</name>  
  10.         <email>jack@email.com</email>  
  11.         <address>china</address>  
  12.         <birthday>  
  13.           <birthday>2010-11-22</birthday>  
  14.         </birthday>  
  15.       </student>  
  16.       <student>  
  17.         <id>0</id>  
  18.         <name>jack</name>  
  19.       </student>  
  20.     </a>  
  21.   </students>  
  22.   <created>  
  23.     <time>1409821431920</time>  
  24.     <timezone>Asia/Shanghai</timezone>  
  25.   </created>  
  26. </com.zdp.domain.Classes>  

4. 将Map集合转成xml文档:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将Map集合转成XML文档 
  3.      */  
  4.     @Test  
  5.     public void writeMap2XML() {  
  6.         try {  
  7.             highLight("====== Map --> XML ======");  
  8.             Map<String, Student> map = new HashMap<String, Student>();  
  9.             map.put("No.1", student);  
  10.   
  11.             student = new Student();  
  12.             student.setAddress("china");  
  13.             student.setEmail("tom@125.com");  
  14.             student.setId(2);  
  15.             student.setName("tom");  
  16.             Birthday day = new Birthday("2010-11-22");  
  17.             student.setBirthday(day);  
  18.             map.put("No.2", student);  
  19.   
  20.             student = new Student();  
  21.             student.setName("jack");  
  22.             map.put("No.3", student);  
  23.   
  24.             xstream.alias("student", Student.class);  
  25.             xstream.alias("key", String.class);  
  26.             xstream.useAttributeFor(Student.class, "id");  
  27.             xstream.useAttributeFor("birthday", String.class);  
  28.             print(xstream.toXML(map));  
  29.         } catch (Exception e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
运行结果:

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  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

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 用OutStream输出流写XML 
  3.      */  
  4.     @Test  
  5.     public void writeXML4OutStream() {  
  6.         try {  
  7.             out = xstream.createObjectOutputStream(System.out);  
  8.             Student stu = new Student();  
  9.             stu.setName("jack");  
  10.             Classes c = new Classes("一班", student, stu);  
  11.             c.setNumber(2);  
  12.             highLight("====== ObjectOutputStream ## JavaObject--> XML ======");  
  13.             out.writeObject(stu);  
  14.             out.writeObject(new Birthday("2010-05-33"));  
  15.             out.write(22);//byte  
  16.             out.writeBoolean(true);  
  17.             out.writeFloat(22.f);  
  18.             out.writeUTF("hello");  
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
运行结果:

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== ObjectOutputStream ## JavaObject--XML ======  
  2. <object-stream>  
  3.   <com.zdp.domain.Student>  
  4.     <id>0</id>  
  5.     <name>jack</name>  
  6.   </com.zdp.domain.Student>  
  7.   <com.zdp.domain.Birthday>  
  8.     <birthday>2010-05-33</birthday>  
  9.   </com.zdp.domain.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对象

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 用InputStream将XML文档转换成java对象  
  3.      */  
  4.     @Test  
  5.     public void readXML4InputStream() {  
  6.         try {  
  7.             String s = "<object-stream><com.zdp.domain.Student><id>0</id><name>jack</name>" +  
  8.               "</com.zdp.domain.Student><com.zdp.domain.Birthday><birthday>2010-05-33</birthday>" +  
  9.               "</com.zdp.domain.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" +  
  10.               "<string>hello</string></object-stream>";  
  11.             highLight("====== ObjectInputStream## XML --> javaObject ======");  
  12.             StringReader reader = new StringReader(s);  
  13.             in = xstream.createObjectInputStream(reader);  
  14.             Student stu = (Student) in.readObject();  
  15.             Birthday b = (Birthday) in.readObject();  
  16.             byte i = in.readByte();  
  17.             boolean bo = in.readBoolean();  
  18.             float f = in.readFloat();  
  19.             String str = in.readUTF();  
  20.             System.out.println(stu);  
  21.             System.out.println(b);  
  22.             System.out.println(i);  
  23.             System.out.println(bo);  
  24.             System.out.println(f);  
  25.             System.out.println(str);  
  26.         } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
运行结果:

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== ObjectInputStream## XML --javaObject ======  
  2. jack#0#null#null#null  
  3. com.zdp.domain.Birthday@27391d  
  4. 22  
  5. true  
  6. 22.0  
  7. hello  

2. 将XML文档转为Java对象:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将XML文档转换成Java对象 
  3.      */  
  4.     @Test  
  5.     public void readXml2Object() {  
  6.         try {  
  7.             highLight("====== Xml >>> Bean ======");  
  8.             Student stu = (Student) xstream.fromXML(xstream.toXML(student));  
  9.             print(stu.toString());  
  10.               
  11.             List<Student> list = new ArrayList<Student>();  
  12.             list.add(student);//add  
  13.               
  14.             Map<String, Student> map = new HashMap<String, Student>();  
  15.             map.put("No.1", student);//put  
  16.               
  17.             student = new Student();  
  18.             student.setAddress("china");  
  19.             student.setEmail("tom@125.com");  
  20.             student.setId(2);  
  21.             student.setName("tom");  
  22.             Birthday day = new Birthday("2010-11-22");  
  23.             student.setBirthday(day);  
  24.             list.add(student);//add  
  25.             map.put("No.2", student);//put  
  26.               
  27.             student = new Student();  
  28.             student.setName("jack");  
  29.             list.add(student);//add  
  30.             map.put("No.3", student);//put  
  31.               
  32.             highLight("====== XML >>> List ======");   
  33.             List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));  
  34.             print("size:" + studetns.size());//3  
  35.             for (Student s : studetns) {  
  36.                 print(s.toString());  
  37.             }  
  38.               
  39.             highLight("====== XML >>> Map ======");  
  40.             Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));  
  41.             print("size:" + maps.size());//3  
  42.             Set<String> key = maps.keySet();  
  43.             Iterator<String> iter = key.iterator();  
  44.             while (iter.hasNext()) {  
  45.                 String k = iter.next();  
  46.                 print(k + ":" + map.get(k));  
  47.             }  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.     }  
运行结果:

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== Xml >>Bean ======  
  2. jack#1#china#com.zdp.domain.Birthday@1125127#jack@email.com  
  3. ====== XML >>List ======  
  4. size:3  
  5. jack#1#china#com.zdp.domain.Birthday@134bed0#jack@email.com  
  6. tom#2#china#com.zdp.domain.Birthday@1db4f6f#tom@125.com  
  7. jack#0#null#null#null  
  8. ====== XML >>Map ======  
  9. size:3  
  10. No.3:jack#0#null#null#null  
  11. No.1:jack#1#china#com.zdp.domain.Birthday@1d520c4#jack@email.com  
  12. No.2:tom#2#china#com.zdp.domain.Birthday@2a5330#tom@125.com  

五. xStream对JSON的支持:

 

xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar

1. 用JettisonMappedXmlDriver完成Java对象到JSON的转换

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON 
  3.      */  
  4.     @Test  
  5.     public void writeEntity2JETTSON() {  
  6.         highLight("====== JettisonMappedXmlDriver === JavaObject >>>> JaonString ======");  
  7.         xstream = new XStream(new JettisonMappedXmlDriver());  
  8.         xstream.setMode(XStream.NO_REFERENCES);  
  9.         xstream.alias("student", Student.class);  
  10.         print(xstream.toXML(student));  
  11.     }  
运行结果:

 

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. ====== JettisonMappedXmlDriver === JavaObject >>>> JaonString ======  
  2. {"student":{"id":1,"name":"jack","email":"jack@email.com","address":"china","birthday":[{},"2010-11-22"]}}  

 

2. 用JsonHierarchicalStreamDriver完成Java对象到JSON的转换

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 转换java对象为JSON字符串 
  3.      */  
  4.     @Test  
  5.     public void writeEntiry2JSON() {  
  6.         highLight("====== JsonHierarchicalStreamDriver === JavaObject >>>> JaonString ======");  
  7.         xstream = new XStream(new JsonHierarchicalStreamDriver());  
  8.         xstream.alias("student", Student.class);  
  9.         highLight("-------Object >>>> JSON---------");  
  10.         print(xstream.toXML(student));  
  11.           
  12.         //删除根节点  
  13.         xstream = new XStream(new JsonHierarchicalStreamDriver() {  
  14.             public HierarchicalStreamWriter createWriter(Writer out) {  
  15.                 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);  
  16.             }  
  17.         });  
  18.           
  19.         xstream.alias("student", Student.class);  
  20.         print(xstream.toXML(student));  
  21.     }  
运行结果:

 

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  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方法,删掉根节点。

 

3. 将List集合转换成JSON串

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将List集合转换成JSON字符串 
  3.      */  
  4.     @Test  
  5.     public void writeList2JSON() {  
  6.         highLight("===== JsonHierarchicalStreamDriver ==== JavaObject >>>> JaonString =====");  
  7.         JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();  
  8.         xstream = new XStream(driver);  
  9.         // xstream = new XStream(new JettisonMappedXmlDriver());//转换错误  
  10.         // xstream.setMode(XStream.NO_REFERENCES);  
  11.         xstream.alias("student", Student.class);  
  12.           
  13.         List<Student> list = new ArrayList<Student>();  
  14.         list.add(student);  
  15.           
  16.         student = new Student();  
  17.         student.setAddress("china");  
  18.         student.setEmail("tom@125.com");  
  19.         student.setId(2);  
  20.         student.setName("tom");  
  21.         Birthday day = new Birthday("2010-11-22");  
  22.         student.setBirthday(day);  
  23.         list.add(student);  
  24.           
  25.         student = new Student();  
  26.         student.setName("jack");  
  27.         list.add(student);  
  28.           
  29.         print(xstream.toXML(list));  
  30.           
  31.         //删除根节点  
  32.         xstream = new XStream(new JsonHierarchicalStreamDriver() {  
  33.             public HierarchicalStreamWriter createWriter(Writer out) {  
  34.                 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);  
  35.             }  
  36.         });  
  37.         xstream.alias("student", Student.class);  
  38.         print(xstream.toXML(list));  
  39.     }  
运行结果:

 

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  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. ]  

 

4. 将Map转换成json串:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将Map集合转换成JSON字符串 
  3.      */  
  4.     @Test  
  5.     public void writeMap2JSON() {  
  6.         highLight("==== JsonHierarchicalStreamDriver ==== Map >>>> JaonString =====");  
  7.         xstream = new XStream(new JsonHierarchicalStreamDriver());  
  8.         xstream.alias("student", Student.class);  
  9.           
  10.         Map<String, Student> map = new HashMap<String, Student>();  
  11.         map.put("No.1", student);  
  12.           
  13.         student = new Student();  
  14.         student.setAddress("china");  
  15.         student.setEmail("tom@125.com");  
  16.         student.setId(2);  
  17.         student.setName("tom");  
  18.         student.setBirthday(new Birthday("2010-11-21"));  
  19.         map.put("No.2", student);  
  20.           
  21.         student = new Student();  
  22.         student.setName("jack");  
  23.         map.put("No.3", student);  
  24.           
  25.         print(xstream.toXML(map));  
  26.           
  27.         //删除根节点  
  28.         xstream = new XStream(new JsonHierarchicalStreamDriver() {  
  29.             public HierarchicalStreamWriter createWriter(Writer out) {  
  30.                 return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);  
  31.             }  
  32.         });  
  33.         xstream  
运行结果:

 

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  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对象:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.      * 将JSON字符串转换成java对象 
  3.      */  
  4.     @Test  
  5.     public void readJSON2Object() throws JSONException {  
  6.         String json = "{student: {" +  
  7.             "id: 1," +  
  8.             "name: haha," +  
  9.             "email: email," +  
  10.             "address: address," +  
  11.             "birthday: {" +  
  12.                "birthday: 2010-11-22 " +  
  13.             "}" +  
  14.         "}}";  
  15.         xstream = new XStream(new JettisonMappedXmlDriver());  
  16.         xstream.alias("student", Student.class);  
  17.         print(xstream.fromXML(json).toString());  
  18.           
  19.         json = "{list: [{" +  
  20.                     "id: 1," +  
  21.                     "name: haha," +  
  22.                     "email: email," +  
  23.                     "address: address," +  
  24.                     "birthday: {" +  
  25.                       "birthday: 2010-11-22" +  
  26.                     "}" +  
  27.                "},{" +  
  28.                     "id: 2," +  
  29.                     "name: tom," +  
  30.                     "email: tom@125.com," +  
  31.                     "address: china," +  
  32.                     "birthday: {" +  
  33.                       "birthday: 2010-11-22" +  
  34.                     "}" +  
  35.                  "}" +  
  36.               "]}";  
  37.         System.out.println(json);   
  38.         List list = (List) xstream.fromXML(json);  
  39.         System.out.println(list.size());  
  40.     }  
运行结果:

 

 

[plain] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. haha#1#address#com.zdp.domain.Birthday@137c60d#email  
  2. {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}}]}  
  3. 0  

 

 

三. 遇到的问题

1. 如何加上xml头部?即<?xml version="1.0" encoding="UTF-8"?>

官方文档是这样解释的:

Why does XStream not write an XML declaration?
XStream is designed to write XML snippets, so you can embed its output into an existing stream or string. 

You can write the XML declaration yourself into the Writer before using it to call XStream.toXML(writer).

我们可以自己添加:XmlDeclarationXStream

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class XmlDeclarationXStream extends XStream {  
  2.     private String version;  
  3.   
  4.     private String ecoding;  
  5.   
  6.     public XmlDeclarationXStream() {  
  7.         this("1.0", "utf-8");  
  8.     }  
  9.   
  10.     public XmlDeclarationXStream(String version, String ecoding) {  
  11.         this.version = version;  
  12.         this.ecoding = ecoding;  
  13.     }  
  14.   
  15.     public String getDeclaration() {  
  16.         return "<?xml version=\"" + this.version + "\" encoding=\"" + this.ecoding + "\"?>";  
  17.     }  
  18.   
  19.     @Override  
  20.     public void toXML(Object obj, OutputStream output) {   
  21.         try {  
  22.             String dec = this.getDeclaration();  
  23.             byte[] bytesOfDec = dec.getBytes(this.ecoding);  
  24.             output.write(bytesOfDec);  
  25.         } catch (Exception e) {  
  26.             throw new RuntimeException("error happens", e);  
  27.         }  
  28.         super.toXML(obj, output);  
  29.     }  
  30.   
  31.     @Override  
  32.     public void toXML(Object obj, Writer writer) {  
  33.         try {  
  34.             writer.write(getDeclaration());   
  35.         } catch (Exception e) {  
  36.             throw new RuntimeException("error happens", e);  
  37.         }  
  38.         super.toXML(obj, writer);  
  39.     }  
  40. }  
测试的时候我们new这个类:XStream xstream = new XmlDeclarationXStream();

 

源码下载:http://download.csdn.net/detail/zdp072/7866129

原文:http://blog.csdn.net/IBM_hoojo/article/details/6342386

 

 

posted on 2015-02-27 01:00  nevergiveupzeng  阅读(505)  评论(0编辑  收藏  举报