xStream转换XML、JSON

时间:2021-11-02 03:42:58
 
 

一. 简介

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

代码结构图:

xStream转换XML、JSON

2. junit测试代码:

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

3. 所需实体类:

(1)Student:

  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

  1. public class Birthday {
  2. private String birthday;
  3. public Birthday() {
  4. }
  5. public Birthday(String birthday) {
  6. this.birthday = birthday;
  7. }
  8. public String getBirthday() {
  9. return birthday;
  10. }
  11. public void setBirthday(String birthday) {
  12. this.birthday = birthday;
  13. }
  14. }

三 Java对象转为xml

1. 将JavaBean转成xml文档:

  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. print("<!-- 重命名后的XML -->");
  11. // 类重命名
  12. xstream.alias("student", Student.class);
  13. xstream.alias("生日", Birthday.class);
  14. xstream.aliasField("生日", Student.class, "birthday");
  15. xstream.aliasField("生日", Birthday.class, "birthday");
  16. // 属性重命名
  17. xstream.aliasField("邮件", Student.class, "email");
  18. // 包重命名
  19. xstream.aliasPackage("zdp", "com.zdp.domain");
  20. print(xstream.toXML(student));
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. }

运行结果:

  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文档:

  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. List<Object> list = new ArrayList<Object>();
  14. // 引用javabean
  15. list.add(student);
  16. list.add(student);
  17. // list.add(listBean); 引用listBean,父元素
  18. student = new Student();
  19. student.setAddress("china");
  20. student.setEmail("tom@125.com");
  21. student.setId(2);
  22. student.setName("tom");
  23. Birthday birthday = new Birthday("2010-11-22");
  24. student.setBirthday(birthday);
  25. list.add(student);
  26. listBean.setList(list);
  27. // 将ListBean中的集合设置空元素,即不显示集合元素标签
  28. // xstream.addImplicitCollection(ListBean.class, "list");
  29. // 设置reference模型
  30. xstream.setMode(XStream.ID_REFERENCES); // id引用
  31. //xstream.setMode(XStream.NO_REFERENCES); // 不引用
  32. //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); // 绝对路径引用
  33. // 将name设置为父类(Student)的元素的属性
  34. xstream.useAttributeFor(Student.class, "name");
  35. xstream.useAttributeFor(Birthday.class, "birthday");
  36. // 修改属性的name
  37. xstream.aliasAttribute("姓名", "name");
  38. xstream.aliasField("生日", Birthday.class, "birthday");
  39. print(xstream.toXML(listBean));
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }

运行结果:

  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代码:

  1. @XStreamAlias("class")
  2. public class Classes {
  3. @XStreamAsAttribute
  4. @XStreamAlias("名称")
  5. private String name;
  6. @XStreamOmitField
  7. private int number;
  8. @XStreamImplicit(itemFieldName = "Students")
  9. private List<Student> students;
  10. @XStreamConverter(SingleValueCalendarConverter.class)
  11. private Calendar created = new GregorianCalendar();
  12. public Classes() {
  13. }
  14. public Classes(String name, Student... stu) {
  15. this.name = name;
  16. this.students = Arrays.asList(stu);
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public int getNumber() {
  25. return number;
  26. }
  27. public void setNumber(int number) {
  28. this.number = number;
  29. }
  30. public List<Student> getStudents() {
  31. return students;
  32. }
  33. public void setStudents(List<Student> students) {
  34. this.students = students;
  35. }
  36. public Calendar getCreated() {
  37. return created;
  38. }
  39. public void setCreated(Calendar created) {
  40. this.created = created;
  41. }
  42. }

(2)编写类型转换器:

  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. public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
  7. GregorianCalendar calendar = new GregorianCalendar();
  8. calendar.setTime(new Date(Long.parseLong(reader.getValue())));
  9. return calendar;
  10. }
  11. public boolean canConvert(Class type) {
  12. return type.equals(GregorianCalendar.class);
  13. }
  14. }

(3)测试代码:

  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. }

运行结果:

  1. ====== annotation Bean --> XML ======
  2. <com.zdp.domain.Classes>
  3. <name>一班</name>
  4. <number>2</number>
  5. <students class="java.util.Arrays$ArrayList">
  6. <a 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文档:

  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. student = new Student();
  11. student.setAddress("china");
  12. student.setEmail("tom@125.com");
  13. student.setId(2);
  14. student.setName("tom");
  15. Birthday day = new Birthday("2010-11-22");
  16. student.setBirthday(day);
  17. map.put("No.2", student);
  18. student = new Student();
  19. student.setName("jack");
  20. map.put("No.3", student);
  21. xstream.alias("student", Student.class);
  22. xstream.alias("key", String.class);
  23. xstream.useAttributeFor(Student.class, "id");
  24. xstream.useAttributeFor("birthday", String.class);
  25. print(xstream.toXML(map));
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }

运行结果:

  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. /**
  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. }

运行结果:

  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对象

  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. }

运行结果:

  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对象:

  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. List<Student> list = new ArrayList<Student>();
  11. list.add(student);//add
  12. Map<String, Student> map = new HashMap<String, Student>();
  13. map.put("No.1", student);//put
  14. student = new Student();
  15. student.setAddress("china");
  16. student.setEmail("tom@125.com");
  17. student.setId(2);
  18. student.setName("tom");
  19. Birthday day = new Birthday("2010-11-22");
  20. student.setBirthday(day);
  21. list.add(student);//add
  22. map.put("No.2", student);//put
  23. student = new Student();
  24. student.setName("jack");
  25. list.add(student);//add
  26. map.put("No.3", student);//put
  27. highLight("====== XML >>> List ======");
  28. List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));
  29. print("size:" + studetns.size());//3
  30. for (Student s : studetns) {
  31. print(s.toString());
  32. }
  33. highLight("====== XML >>> Map ======");
  34. Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));
  35. print("size:" + maps.size());//3
  36. Set<String> key = maps.keySet();
  37. Iterator<String> iter = key.iterator();
  38. while (iter.hasNext()) {
  39. String k = iter.next();
  40. print(k + ":" + map.get(k));
  41. }
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }

运行结果:

  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的转换

  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. }

运行结果:

  1. ====== JettisonMappedXmlDriver === JavaObject >>>> JaonString ======
  2. {"student":{"id":1,"name":"jack","email":"jack@email.com","address":"china","birthday":[{},"2010-11-22"]}}

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

  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. xstream = new XStream(new JsonHierarchicalStreamDriver() {
  13. public HierarchicalStreamWriter createWriter(Writer out) {
  14. return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
  15. }
  16. });
  17. xstream.alias("student", Student.class);
  18. print(xstream.toXML(student));
  19. }

运行结果:

  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串

  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. List<Student> list = new ArrayList<Student>();
  13. list.add(student);
  14. student = new Student();
  15. student.setAddress("china");
  16. student.setEmail("tom@125.com");
  17. student.setId(2);
  18. student.setName("tom");
  19. Birthday day = new Birthday("2010-11-22");
  20. student.setBirthday(day);
  21. list.add(student);
  22. student = new Student();
  23. student.setName("jack");
  24. list.add(student);
  25. print(xstream.toXML(list));
  26. //删除根节点
  27. xstream = new XStream(new JsonHierarchicalStreamDriver() {
  28. public HierarchicalStreamWriter createWriter(Writer out) {
  29. return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
  30. }
  31. });
  32. xstream.alias("student", Student.class);
  33. print(xstream.toXML(list));
  34. }

运行结果:

  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串:

  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. Map<String, Student> map = new HashMap<String, Student>();
  10. map.put("No.1", student);
  11. student = new Student();
  12. student.setAddress("china");
  13. student.setEmail("tom@125.com");
  14. student.setId(2);
  15. student.setName("tom");
  16. student.setBirthday(new Birthday("2010-11-21"));
  17. map.put("No.2", student);
  18. student = new Student();
  19. student.setName("jack");
  20. map.put("No.3", student);
  21. print(xstream.toXML(map));
  22. //删除根节点
  23. xstream = new XStream(new JsonHierarchicalStreamDriver() {
  24. public HierarchicalStreamWriter createWriter(Writer out) {
  25. return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
  26. }
  27. });
  28. xstream

运行结果:

  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. * 将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. json = "{list: [{" +
  19. "id: 1," +
  20. "name: haha," +
  21. "email: email," +
  22. "address: address," +
  23. "birthday: {" +
  24. "birthday: 2010-11-22" +
  25. "}" +
  26. "},{" +
  27. "id: 2," +
  28. "name: tom," +
  29. "email: tom@125.com," +
  30. "address: china," +
  31. "birthday: {" +
  32. "birthday: 2010-11-22" +
  33. "}" +
  34. "}" +
  35. "]}";
  36. System.out.println(json);
  37. List list = (List) xstream.fromXML(json);
  38. System.out.println(list.size());
  39. }

运行结果:

  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

  1. public class XmlDeclarationXStream extends XStream {
  2. private String version;
  3. private String ecoding;
  4. public XmlDeclarationXStream() {
  5. this("1.0", "utf-8");
  6. }
  7. public XmlDeclarationXStream(String version, String ecoding) {
  8. this.version = version;
  9. this.ecoding = ecoding;
  10. }
  11. public String getDeclaration() {
  12. return "<?xml version=\"" + this.version + "\" encoding=\"" + this.ecoding + "\"?>";
  13. }
  14. @Override
  15. public void toXML(Object obj, OutputStream output) {
  16. try {
  17. String dec = this.getDeclaration();
  18. byte[] bytesOfDec = dec.getBytes(this.ecoding);
  19. output.write(bytesOfDec);
  20. } catch (Exception e) {
  21. throw new RuntimeException("error happens", e);
  22. }
  23. super.toXML(obj, output);
  24. }
  25. @Override
  26. public void toXML(Object obj, Writer writer) {
  27. try {
  28. writer.write(getDeclaration());
  29. } catch (Exception e) {
  30. throw new RuntimeException("error happens", e);
  31. }
  32. super.toXML(obj, writer);
  33. }
  34. }

测试的时候我们new这个类:XStream xstream = new XmlDeclarationXStream();

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

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