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

  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("[email protected]");
  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:

[java] view plaincopy

  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

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

[java] view plaincopy

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

运行结果:

[html] view plaincopy

  1. ====== Bean -> XML ======
  2. <!-- 没有重命名的XML -->
  3. <com.zdp.domain.Student>
  4. <id>1</id>
  5. <name>jack</name>
  6. <email>[email protected]</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. <邮件>[email protected]</邮件>
  17. <address>china</address>
  18. <生日>
  19. <生日>2010-11-22</生日>
  20. </生日>
  21. </student>

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

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

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

[java] view plaincopy

  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("[email protected]");
  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. }

运行结果:

[html] view plaincopy

  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>[email protected]</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>[email protected]</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

  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)编写类型转换器:

[java] view plaincopy

  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)测试代码:

[java] view plaincopy

  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

  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>[email protected]</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

  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("[email protected]");
  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. }

运行结果:

[html] view plaincopy

  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>[email protected]</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>[email protected]</email>
  23. <address>china</address>
  24. <birthday birthday="2010-11-22"/>
  25. </student>
  26. </entry>
  27. </map>

5. 用OutStream输出流写XML

[java] view plaincopy

  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

  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

  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

  1. ====== ObjectInputStream## XML --> javaObject ======
  2. jack#0#null#null#null
  3. [email protected]
  4. 22
  5. true
  6. 22.0
  7. hello

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

[java] view plaincopy

  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("[email protected]");
  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. }

运行结果:

[html] view plaincopy

  1. ====== Xml >>> Bean ======
  2. jack#1#china#[email protected]#[email protected]email.com
  3. ====== XML >>> List ======
  4. size:3
  5. jack#1#china#[email protected]#[email protected]
  6. tom#2#china#[email protected]#[email protected]
  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#[email protected]#[email protected]
  12. No.2:tom#2#china#[email protected]#[email protected]

五. xStream对JSON的支持:

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

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

[java] view plaincopy

  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

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

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

[java] view plaincopy

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

运行结果:

[plain] view plaincopy

  1. ====== JsonHierarchicalStreamDriver === JavaObject >>>> JaonString ======
  2. -------Object >>>> JSON---------
  3. {"student": {
  4. "id": 1,
  5. "name": "jack",
  6. "email": "[email protected]",
  7. "address": "china",
  8. "birthday": {
  9. "birthday": "2010-11-22"
  10. }
  11. }}
  12. {
  13. "id": 1,
  14. "name": "jack",
  15. "email": "[email protected]",
  16. "address": "china",
  17. "birthday": {
  18. "birthday": "2010-11-22"
  19. }
  20. }

使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,

你可以重写createWriter方法,删掉根节点。

3. 将List集合转换成JSON串

[java] view plaincopy

  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("[email protected]");
  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. }

运行结果:

[plain] view plaincopy

  1. ===== JsonHierarchicalStreamDriver ==== JavaObject >>>> JaonString =====
  2. {"list": [
  3. {
  4. "id": 1,
  5. "name": "jack",
  6. "email": "[email protected]",
  7. "address": "china",
  8. "birthday": {
  9. "birthday": "2010-11-22"
  10. }
  11. },
  12. {
  13. "id": 2,
  14. "name": "tom",
  15. "email": "[email protected]",
  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": "[email protected]",
  31. "address": "china",
  32. "birthday": {
  33. "birthday": "2010-11-22"
  34. }
  35. },
  36. {
  37. "id": 2,
  38. "name": "tom",
  39. "email": "[email protected]",
  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

  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("[email protected]");
  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

运行结果:

[plain] view plaincopy

  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": "[email protected]",
  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": "[email protected]",
  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": "[email protected]",
  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": "[email protected]",
  61. "address": "china",
  62. "birthday": {
  63. "birthday": "2010-11-21"
  64. }
  65. }
  66. ]
  67. ]

5. 将JSON转换成Java对象:

[java] view plaincopy

  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: [email protected]," +
  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. }

运行结果:

[plain] view plaincopy

  1. haha#1#address#[email protected]#email
  2. {list: [{id: 1,name: haha,email: email,address: address,birthday: {birthday: 2010-11-22}},{id: 2,name: tom,email: [email protected],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

  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

时间: 2024-10-17 15:54:02

xStream转换XML、JSON的相关文章

xStream完美转换XML、JSON

xStream框架 xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换: 它们都完美支持JSON,但是对xml的支持还不是很好.一定程度上限制了对Java对象的描述,不能让xml完全体现到对Java对象的描述.这里将会介绍xStream对JSON.XML的完美支持.xStream不仅对XML的转换非常友好,而且提供annotation注解,可以在JavaBean中完成对xml节点.属性的描述.以及对JSON也支持,只需要提供

X-stream完美转换XML、JSON

一.准备工作 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-

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,

XStream实现xml和java对象之间的互相转换,同理JSON也可以

首先去官网下载响应JAR包 http://xstream.codehaus.org/index.html 最少需要两个jar包,一个xstream.jar,一个是xmlpull.jar 首先来看下java对象到xml的转换 package xml; class PhoneNumber { private int code; private int number; public int getCode() { return code; } public void setCode(int code)

XStream解析xml和json

XStream是一个在我看来比较好的一个第三方包了.因为它在解析时支持注解.这样很是方便,并且xml跟json这两种格式的文件都能进行解析,XStream本属于java的一个第三方包,甚是好用,若是拿它在android开发环境,也是能正常解析,但有点美中不足,因为android开发环境时,XStream不太支持json转对象,只支持对象转json,其他xml与对象的互转都支持.这样的话双解析就有了那么一点瑕疵之处,不过话说回来,没多少需求的数据交互会用json跟xml切来切去的,当只是json转

java将XML文档转换成json格式数据

功能 将xml文档转换成json格式数据 说明 依赖包: 1. jdom-2.0.2.jar : xml解析工具包; 2. fastjson-1.1.36.jar : 阿里巴巴研发的高性能json工具包 程序源码 package com.xxx.open.pay.util; import com.alibaba.fastjson.JSONObject; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdo

接口测试xml格式转换成json

未经允许,禁止转载!!!! 接口测试一般返回的是xml和json,现在大多数时候是返回成json的格式,但是有时候也会出现xml格式, 由于xml格式的文件阅读起来不是很容易懂,所以尽量将xml转换成json文件容易理解. 提供两个网站可以将xml转换成json : http://tool.chinaz.com/tools/json2xml.aspx http://www.bejson.com/xml2json/ 下面我们就开始讲接口测试返回的xml数据转换成json 下载一个软件,名叫Edit

xstream 实现xml和对象转换

1.jar包 xstream-1.4.2.jar     xpp3_min-1.1.4c.jar 2.工具类 package com.core.util; import java.lang.reflect.Field; import java.util.Iterator; import java.util.List; import java.util.Map; import com.core.model.Mobile; import com.thoughtworks.xstream.XStrea

java转换xml、list、map和json

java转换xml.list.map和json [java] view plaincopy package com.shine.framework.core.util; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; i