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

public class XStreamTest {
	private XStream xstream;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private Student student;

	/**
	 * 初始化资源准备
	 */
	@Before
	public void init() {
		try {
			xstream = new XStream(new DomDriver());
		} catch (Exception e) {
			e.printStackTrace();
		}
		student = new Student();
		student.setAddress("china");
		student.setEmail("[email protected]");
		student.setId(1);
		student.setName("jack");
		Birthday birthday = new Birthday(); 
		birthday.setBirthday("2010-11-22");
		student.setBirthday(birthday);
	}

	/**
	 * 释放对象资源
	 */
	@After
	public void destory() {
		xstream = null;
		student = null;
		try {
			if (out != null) {
				out.flush();
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.gc();
	}
	
	/**
	 * 打印字符串
	 */
	public final void print(String string) { 
		System.out.println(string);
	}
	
	/**
	 * 高亮字符串
	 */
	public final void highLight(String string) {
		System.err.println(string);
	}

}

3. 所需实体类:

(1)Student:

public class Student {
	private int id;
	private String name;
	private String email;
	private String address;
	private Birthday birthday;
	// getter and setter
	public String toString() {
		return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
	}
}


(2)Birthday

public class Birthday {
	private String birthday;

	public Birthday() {
	}
	
	public Birthday(String birthday) {
		this.birthday = birthday;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
}

三 Java对象转为xml

1. 将JavaBean转成xml文档:

/** 
	 * Java对象转换成XML
	 */
	@Test
	public void writeBean2XML() {
		try {
			highLight("====== Bean -> XML ======");
			print("<!-- 没有重命名的XML -->");
			print(xstream.toXML(student));
			
			print("<!-- 重命名后的XML -->");
			// 类重命名
			xstream.alias("student", Student.class);
			xstream.alias("生日", Birthday.class);
			xstream.aliasField("生日", Student.class, "birthday");
			xstream.aliasField("生日", Birthday.class, "birthday");

			// 属性重命名
			xstream.aliasField("邮件", Student.class, "email");

			// 包重命名
			xstream.aliasPackage("zdp", "com.zdp.domain");
			print(xstream.toXML(student));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


运行结果:

====== Bean -> XML ======
<!-- 没有重命名的XML -->
<com.zdp.domain.Student>
  <id>1</id>
  <name>jack</name>
  <email>[email protected]</email>
  <address>china</address>
  <birthday>
    <birthday>2010-11-22</birthday>
  </birthday>
</com.zdp.domain.Student>
<!-- 重命名后的XML -->
<student>
  <id>1</id>
  <name>jack</name>
  <邮件>[email protected]</邮件>
  <address>china</address>
  <生日>
    <生日>2010-11-22</生日>
  </生日>
</student>

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

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


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

/**
	 * 将List集合转换成XML对象
	 */
	@Test
	public void writeList2XML() {
		try {
			// 修改元素名称
			highLight("====== List --> XML ======");
			xstream.alias("beans", ListBean.class);
			xstream.alias("student", Student.class);
			ListBean listBean = new ListBean();
			listBean.setName("this is a List Collection");

			List<Object> list = new ArrayList<Object>();
			// 引用javabean
			list.add(student);
			list.add(student); 
			// list.add(listBean); 引用listBean,父元素

			student = new Student();
			student.setAddress("china");
			student.setEmail("[email protected]");
			student.setId(2);
			student.setName("tom");
			Birthday birthday = new Birthday("2010-11-22"); 
			student.setBirthday(birthday);

			list.add(student);
			listBean.setList(list);
			
			// 将ListBean中的集合设置空元素,即不显示集合元素标签
	        // xstream.addImplicitCollection(ListBean.class, "list");
			
			// 设置reference模型
			xstream.setMode(XStream.ID_REFERENCES); // id引用
	        //xstream.setMode(XStream.NO_REFERENCES); // 不引用
	        //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); // 绝对路径引用
			
			// 将name设置为父类(Student)的元素的属性
	        xstream.useAttributeFor(Student.class, "name");
	        xstream.useAttributeFor(Birthday.class, "birthday");
			
			// 修改属性的name
			xstream.aliasAttribute("姓名", "name");
			xstream.aliasField("生日", Birthday.class, "birthday");

			print(xstream.toXML(listBean));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


运行结果:

====== List --> XML ======
<beans id="1">
  <name>this is a List Collection</name>
  <list id="2">
    <student id="3" 姓名="jack">
      <id>1</id>
      <email>[email protected]</email>
      <address>china</address>
      <birthday id="4" 生日="2010-11-22"/>
    </student>
    <student reference="3"/>
    <student id="5" 姓名="tom">
      <id>2</id>
      <email>[email protected]</email>
      <address>china</address>
      <birthday id="6" 生日="2010-11-22"/>
    </student>
  </list>
</beans>







郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。