一、准备工作
1、 下载jar包、及官方资源
xStream的jar下载地址:
官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html
添加xstream-1.3.1.jar文件到工程中,就可以开始下面的工作;需要的jar如下:
2、 测试用例代码
package com.hoo.test;
<!--CRLF-->
<!--CRLF-->
import java.io.IOException;
<!--CRLF-->
import java.io.ObjectInputStream;
<!--CRLF-->
import java.io.ObjectOutputStream;
<!--CRLF-->
import java.io.StringReader;
<!--CRLF-->
import java.io.Writer;
<!--CRLF-->
import java.util.ArrayList;
<!--CRLF-->
import java.util.HashMap;
<!--CRLF-->
import java.util.Iterator;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import java.util.Map;
<!--CRLF-->
import java.util.Set;
<!--CRLF-->
import org.codehaus.jettison.json.JSONException;
<!--CRLF-->
import org.junit.After;
<!--CRLF-->
import org.junit.Before;
<!--CRLF-->
import org.junit.Test;
<!--CRLF-->
import com.hoo.entity.Birthday;
<!--CRLF-->
import com.hoo.entity.Classes;
<!--CRLF-->
import com.hoo.entity.ListBean;
<!--CRLF-->
import com.hoo.entity.Student;
<!--CRLF-->
import com.thoughtworks.xstream.XStream;
<!--CRLF-->
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
<!--CRLF-->
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
<!--CRLF-->
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
<!--CRLF-->
import com.thoughtworks.xstream.io.json.JsonWriter;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>Java对象和XML字符串的相互转换
<!--CRLF-->
* jar-lib-version: xstream-1.3.1
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 12:15:15 PM
<!--CRLF-->
* @file XStreamTest.java
<!--CRLF-->
* @package com.hoo.test
<!--CRLF-->
* @project WebHttpUtils
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email [email protected]
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@SuppressWarnings("unchecked")
<!--CRLF-->
public class XStreamTest {<!--CRLF-->
<!--CRLF-->
private XStream xstream = null;
<!--CRLF-->
private ObjectOutputStream out = null;
<!--CRLF-->
private ObjectInputStream in = null;
<!--CRLF-->
<!--CRLF-->
private Student bean = null;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>初始化资源准备
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 12:16:28 PM
<!--CRLF-->
*/
<!--CRLF-->
@Before<!--CRLF-->
public void init() {<!--CRLF-->
try {
<!--CRLF-->
xstream = new XStream();
<!--CRLF-->
//xstream = new XStream(new DomDriver()); // 需要xpp3 jar
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(1);<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
Birthday day = new Birthday();
<!--CRLF-->
day.setBirthday("2010-11-22");
<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* <b>function:</b>释放对象资源
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 12:16:38 PM
<!--CRLF-->
*/
<!--CRLF-->
@After<!--CRLF-->
public void destory() {<!--CRLF-->
xstream = null;<!--CRLF-->
bean = null;<!--CRLF-->
try {
<!--CRLF-->
if (out != null) {
<!--CRLF-->
out.flush();<!--CRLF-->
out.close();<!--CRLF-->
}<!--CRLF-->
if (in != null) {
<!--CRLF-->
in.close();<!--CRLF-->
}<!--CRLF-->
} catch (IOException e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
System.gc();<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public final void fail(String string) {<!--CRLF-->
System.out.println(string);<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public final void failRed(String string) {<!--CRLF-->
System.err.println(string);<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
通过XStream对象的toXML方法就可以完成Java对象到XML的转换,toXML方法还有2个相同签名的方法,需要传递一个流。然后通过流来完成xml信息的输出。
3、 需要的JavaBean
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
public class Student {<!--CRLF-->
private int id;<!--CRLF-->
private String name;
<!--CRLF-->
private String email;
<!--CRLF-->
private String address;
<!--CRLF-->
private Birthday birthday;
<!--CRLF-->
//getter、setter
<!--CRLF-->
public String toString() {
<!--CRLF-->
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
二、Java转换成XML
1、 JavaBean转换XM
/**
<!--CRLF-->
* <b>function:</b>Java对象转换成XML字符串
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 12:19:01 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeBean2XML() {<!--CRLF-->
try {
<!--CRLF-->
fail("------------Bean->XML------------");
<!--CRLF-->
fail(xstream.toXML(bean));<!--CRLF-->
fail("重命名后的XML");
<!--CRLF-->
//类重命名
<!--CRLF-->
//xstream.alias("account", Student.class);
<!--CRLF-->
//xstream.alias("生日", Birthday.class);
<!--CRLF-->
//xstream.aliasField("生日", Student.class, "birthday");
<!--CRLF-->
//xstream.aliasField("生日", Birthday.class, "birthday");
<!--CRLF-->
//fail(xstream.toXML(bean));
<!--CRLF-->
//属性重命名
<!--CRLF-->
xstream.aliasField("邮件", Student.class, "email");<!--CRLF-->
//包重命名
<!--CRLF-->
xstream.aliasPackage("hoo", "com.hoo.entity");<!--CRLF-->
fail(xstream.toXML(bean));<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
看结果中的第一份xml内容,是没有经过然后修改或重命名的文档,按照原样输出。文档中的第二份文档的package经过重命名,email属性也经过重命名以及类名也可以进行重命名的。
运行后结果如下:
------------Bean->XML------------
<!--CRLF-->
<com.hoo.entity.Student><!--CRLF-->
<id>1</id><!--CRLF-->
<name>jack</name><!--CRLF-->
<email>jack@email.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday><!--CRLF-->
<birthday>2010-11-22</birthday><!--CRLF-->
</birthday><!--CRLF-->
</com.hoo.entity.Student><!--CRLF-->
重命名后的XML<!--CRLF-->
<hoo.Student><!--CRLF-->
<id>1</id><!--CRLF-->
<name>jack</name><!--CRLF-->
<邮件>jack@email.com</邮件><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday><!--CRLF-->
<birthday>2010-11-22</birthday><!--CRLF-->
</birthday><!--CRLF-->
</hoo.Student><!--CRLF-->
2、 将List集合转换成xml文档
/**
<!--CRLF-->
* <b>function:</b>将Java的List集合转换成XML对象
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 12:20:07 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeList2XML() {<!--CRLF-->
try {
<!--CRLF-->
//修改元素名称
<!--CRLF-->
xstream.alias("beans", ListBean.class);<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail("----------List-->XML----------");
<!--CRLF-->
ListBean listBean = new ListBean();
<!--CRLF-->
listBean.setName("this is a List Collection");
<!--CRLF-->
<!--CRLF-->
List<Object> list = new ArrayList<Object>();
<!--CRLF-->
list.add(bean);<!--CRLF-->
list.add(bean);//引用bean
<!--CRLF-->
//list.add(listBean);//引用listBean,父元素
<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(2);<!--CRLF-->
bean.setName("tom");
<!--CRLF-->
Birthday day = new Birthday("2010-11-22");<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
<!--CRLF-->
list.add(bean);<!--CRLF-->
listBean.setList(list);<!--CRLF-->
<!--CRLF-->
//将ListBean中的集合设置空元素,即不显示集合元素标签
<!--CRLF-->
//xstream.addImplicitCollection(ListBean.class, "list");
<!--CRLF-->
<!--CRLF-->
//设置reference模型
<!--CRLF-->
//xstream.setMode(XStream.NO_REFERENCES);//不引用
<!--CRLF-->
xstream.setMode(XStream.ID_REFERENCES);//id引用
<!--CRLF-->
//xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用
<!--CRLF-->
<!--CRLF-->
//将name设置为父类(Student)的元素的属性
<!--CRLF-->
xstream.useAttributeFor(Student.class, "name");<!--CRLF-->
xstream.useAttributeFor(Birthday.class, "birthday");<!--CRLF-->
//修改属性的name
<!--CRLF-->
xstream.aliasAttribute("姓名", "name");<!--CRLF-->
xstream.aliasField("生日", Birthday.class, "birthday");<!--CRLF-->
<!--CRLF-->
fail(xstream.toXML(listBean));<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
上面的代码运行后,结果如下:
----------List-->XML----------
<!--CRLF-->
<beans id="1"><!--CRLF-->
<name>this is a List Collection</name><!--CRLF-->
<list id="2"><!--CRLF-->
<student id="3" 姓名="jack"><!--CRLF-->
<id>1</id><!--CRLF-->
<email>jack@email.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday id="4" 生日="2010-11-22"/><!--CRLF-->
</student><!--CRLF-->
<student reference="3"/><!--CRLF-->
<student id="5" 姓名="tom"><!--CRLF-->
<id>2</id><!--CRLF-->
<email>tom@125.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday id="6" 生日="2010-11-22"/><!--CRLF-->
</student><!--CRLF-->
</list><!--CRLF-->
</beans><!--CRLF-->
如果不加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的代码
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
import java.util.Arrays;
<!--CRLF-->
import java.util.Calendar;
<!--CRLF-->
import java.util.GregorianCalendar;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import com.thoughtworks.xstream.annotations.XStreamAlias;
<!--CRLF-->
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
<!--CRLF-->
import com.thoughtworks.xstream.annotations.XStreamConverter;
<!--CRLF-->
import com.thoughtworks.xstream.annotations.XStreamImplicit;
<!--CRLF-->
import com.thoughtworks.xstream.annotations.XStreamOmitField;
<!--CRLF-->
<!--CRLF-->
@XStreamAlias("class")
<!--CRLF-->
public class Classes {<!--CRLF-->
<!--CRLF-->
/*
<!--CRLF-->
* 设置属性显示
<!--CRLF-->
*/
<!--CRLF-->
@XStreamAsAttribute<!--CRLF-->
@XStreamAlias("名称")
<!--CRLF-->
private String name;
<!--CRLF-->
<!--CRLF-->
/*
<!--CRLF-->
* 忽略
<!--CRLF-->
*/
<!--CRLF-->
@XStreamOmitField<!--CRLF-->
private int number;<!--CRLF-->
<!--CRLF-->
@XStreamImplicit(itemFieldName = "Students")
<!--CRLF-->
private List<Student> students;
<!--CRLF-->
<!--CRLF-->
@SuppressWarnings("unused")
<!--CRLF-->
@XStreamConverter(SingleValueCalendarConverter.class)
<!--CRLF-->
private Calendar created = new GregorianCalendar();<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
public Classes(){}
<!--CRLF-->
public Classes(String name, Student... stu) {
<!--CRLF-->
this.name = name;
<!--CRLF-->
this.students = Arrays.asList(stu);
<!--CRLF-->
}<!--CRLF-->
//getter、setter
<!--CRLF-->
}<!--CRLF-->
SingleValueCalendarConverter.java这个是一个类型转换器
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
import java.util.Calendar;
<!--CRLF-->
import java.util.Date;
<!--CRLF-->
import java.util.GregorianCalendar;
<!--CRLF-->
import com.thoughtworks.xstream.converters.Converter;
<!--CRLF-->
import com.thoughtworks.xstream.converters.MarshallingContext;
<!--CRLF-->
import com.thoughtworks.xstream.converters.UnmarshallingContext;
<!--CRLF-->
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
<!--CRLF-->
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
<!--CRLF-->
<!--CRLF-->
public class SingleValueCalendarConverter implements Converter {<!--CRLF-->
public void marshal(Object source, HierarchicalStreamWriter writer,<!--CRLF-->
MarshallingContext context) {<!--CRLF-->
Calendar calendar = (Calendar) source;<!--CRLF-->
writer.setValue(String.valueOf(calendar.getTime().getTime()));<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
public Object unmarshal(HierarchicalStreamReader reader,
<!--CRLF-->
UnmarshallingContext context) {<!--CRLF-->
GregorianCalendar calendar = new GregorianCalendar();
<!--CRLF-->
calendar.setTime(new Date(Long.parseLong(reader.getValue())));
<!--CRLF-->
return calendar;
<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
@SuppressWarnings("unchecked")
<!--CRLF-->
public boolean canConvert(Class type) {<!--CRLF-->
return type.equals(GregorianCalendar.class);<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
再看看测试用例代码
@Test<!--CRLF-->
public void writeList2XML4Annotation() {<!--CRLF-->
try {
<!--CRLF-->
failRed("---------annotation Bean --> XML---------");
<!--CRLF-->
Student stu = new Student();
<!--CRLF-->
stu.setName("jack");
<!--CRLF-->
Classes c = new Classes("一班", bean, stu);<!--CRLF-->
c.setNumber(2);<!--CRLF-->
//对指定的类使用Annotation
<!--CRLF-->
//xstream.processAnnotations(Classes.class);
<!--CRLF-->
//启用Annotation
<!--CRLF-->
//xstream.autodetectAnnotations(true);
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.toXML(c));<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
当启用annotation或是对某个特定的类启用annotation时,上面的classes这个类才有效果。如果不启用annotation,运行后结果如下:
---------annotation Bean --> XML---------
<!--CRLF-->
<com.hoo.entity.Classes><!--CRLF-->
<name>一班</name><!--CRLF-->
<number>2</number><!--CRLF-->
<students class="java.util.Arrays$ArrayList"><!--CRLF-->
<a class="student-array"><!--CRLF-->
<student><!--CRLF-->
<id>1</id><!--CRLF-->
<name>jack</name><!--CRLF-->
<email>jack@email.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday><!--CRLF-->
<birthday>2010-11-22</birthday><!--CRLF-->
</birthday><!--CRLF-->
</student><!--CRLF-->
<student><!--CRLF-->
<id>0</id><!--CRLF-->
<name>jack</name><!--CRLF-->
</student><!--CRLF-->
</a><!--CRLF-->
</students><!--CRLF-->
<created><!--CRLF-->
<time>1303292056718</time><!--CRLF-->
<timezone>Asia/Shanghai</timezone><!--CRLF-->
</created><!--CRLF-->
</com.hoo.entity.Classes><!--CRLF-->
当启用annotation后xstream.processAnnotations(Classes.class),结果如下:
---------annotation Bean --> XML---------
<!--CRLF-->
<class 名称="一班"><!--CRLF-->
<Students><!--CRLF-->
<id>1</id><!--CRLF-->
<name>jack</name><!--CRLF-->
<email>jack@email.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday><!--CRLF-->
<birthday>2010-11-22</birthday><!--CRLF-->
</birthday><!--CRLF-->
</Students><!--CRLF-->
<Students><!--CRLF-->
<id>0</id><!--CRLF-->
<name>jack</name><!--CRLF-->
</Students><!--CRLF-->
<created>1303292242937</created><!--CRLF-->
</class><!--CRLF-->
4、 Map集合转换xml文档
/**
<!--CRLF-->
* <b>function:</b>Java Map集合转XML
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:13:26 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeMap2XML() {<!--CRLF-->
try {
<!--CRLF-->
failRed("---------Map --> XML---------");
<!--CRLF-->
Map<String, Student> map = new HashMap<String, Student>();
<!--CRLF-->
map.put("No.1", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(2);<!--CRLF-->
bean.setName("tom");
<!--CRLF-->
Birthday day = new Birthday("2010-11-22");<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
map.put("No.2", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
map.put("No.3", bean);//put<!--CRLF-->
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
xstream.alias("key", String.class);<!--CRLF-->
xstream.useAttributeFor(Student.class, "id");<!--CRLF-->
xstream.useAttributeFor("birthday", String.class);<!--CRLF-->
fail(xstream.toXML(map));<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
---------Map --> XML---------
<!--CRLF-->
<map><!--CRLF-->
<entry><!--CRLF-->
<key>No.3</key><!--CRLF-->
<student id="0"><!--CRLF-->
<name>jack</name><!--CRLF-->
</student><!--CRLF-->
</entry><!--CRLF-->
<entry><!--CRLF-->
<key>No.1</key><!--CRLF-->
<student id="1"><!--CRLF-->
<name>jack</name><!--CRLF-->
<email>jack@email.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday birthday="2010-11-22"/><!--CRLF-->
</student><!--CRLF-->
</entry><!--CRLF-->
<entry><!--CRLF-->
<key>No.2</key><!--CRLF-->
<student id="2"><!--CRLF-->
<name>tom</name><!--CRLF-->
<email>tom@125.com</email><!--CRLF-->
<address>china</address><!--CRLF-->
<birthday birthday="2010-11-22"/><!--CRLF-->
</student><!--CRLF-->
</entry><!--CRLF-->
</map><!--CRLF-->
5、 用OutStream输出流写XML
/**
<!--CRLF-->
* <b>function:</b>用OutStream输出流写XML
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:13:48 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeXML4OutStream() {<!--CRLF-->
try {
<!--CRLF-->
out = xstream.createObjectOutputStream(System.out);<!--CRLF-->
Student stu = new Student();
<!--CRLF-->
stu.setName("jack");
<!--CRLF-->
Classes c = new Classes("一班", bean, stu);<!--CRLF-->
c.setNumber(2);<!--CRLF-->
failRed("---------ObjectOutputStream # JavaObject--> XML---------");
<!--CRLF-->
out.writeObject(stu);<!--CRLF-->
out.writeObject(new Birthday("2010-05-33"));<!--CRLF-->
out.write(22);//byte
<!--CRLF-->
out.writeBoolean(true);<!--CRLF-->
out.writeFloat(22.f);<!--CRLF-->
out.writeUTF("hello");
<!--CRLF-->
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
使用输出流后,可以通过流对象完成xml的构建,即使没有JavaBean对象,你可以用流来构建一个复杂的xml文档,运行后结果如下:
---------ObjectOutputStream # JavaObject--> XML---------
<!--CRLF-->
<object-stream><!--CRLF-->
<com.hoo.entity.Student><!--CRLF-->
<id>0</id><!--CRLF-->
<name>jack</name><!--CRLF-->
</com.hoo.entity.Student><!--CRLF-->
<com.hoo.entity.Birthday><!--CRLF-->
<birthday>2010-05-33</birthday><!--CRLF-->
</com.hoo.entity.Birthday><!--CRLF-->
<byte>22</byte><!--CRLF-->
<boolean>true</boolean><!--CRLF-->
<float>22.0</float><!--CRLF-->
<string>hello</string><!--CRLF-->
</object-stream><!--CRLF-->
三、XML内容转换Java对象
1、 用InputStream将XML文档转换成java对象
/**
<!--CRLF-->
* <b>function:</b>用InputStream将XML文档转换成java对象
<!--CRLF-->
* 需要额外的jar xpp3-main.jar
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:14:52 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void readXML4InputStream() {<!--CRLF-->
try {
<!--CRLF-->
String s = "<object-stream><com.hoo.entity.Student><id>0</id><name>jack</name>" +
<!--CRLF-->
"</com.hoo.entity.Student><com.hoo.entity.Birthday><birthday>2010-05-33</birthday>" +
<!--CRLF-->
"</com.hoo.entity.Birthday><byte>22</byte><boolean>true</boolean><float>22.0</float>" +
<!--CRLF-->
"<string>hello</string></object-stream>";
<!--CRLF-->
failRed("---------ObjectInputStream## XML --> javaObject---------");
<!--CRLF-->
StringReader reader = new StringReader(s);
<!--CRLF-->
in = xstream.createObjectInputStream(reader);<!--CRLF-->
Student stu = (Student) in.readObject();<!--CRLF-->
Birthday b = (Birthday) in.readObject();<!--CRLF-->
byte i = in.readByte();
<!--CRLF-->
boolean bo = in.readBoolean();
<!--CRLF-->
float f = in.readFloat();
<!--CRLF-->
String str = in.readUTF();<!--CRLF-->
System.out.println(stu);<!--CRLF-->
System.out.println(b);<!--CRLF-->
System.out.println(i);<!--CRLF-->
System.out.println(bo);<!--CRLF-->
System.out.println(f);<!--CRLF-->
System.out.println(str);<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
读取后,转换的Java对象,结果如下:
---------ObjectInputStream## XML --> javaObject---------<!--CRLF-->
jack#0#null#null#null<!--CRLF-->
2010-05-33<!--CRLF-->
22<!--CRLF-->
true<!--CRLF-->
22.0<!--CRLF-->
hello<!--CRLF-->
2、 将xml文档转换成Java对象
/**
<!--CRLF-->
* <b>function:</b>将XML字符串转换成Java对象
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 2:39:06 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void readXml2Object() {<!--CRLF-->
try {
<!--CRLF-->
failRed("-----------Xml >>> Bean--------------");
<!--CRLF-->
Student stu = (Student) xstream.fromXML(xstream.toXML(bean));<!--CRLF-->
fail(stu.toString());<!--CRLF-->
<!--CRLF-->
List<Student> list = new ArrayList<Student>();
<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
<!--CRLF-->
Map<String, Student> map = new HashMap<String, Student>();
<!--CRLF-->
map.put("No.1", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(2);<!--CRLF-->
bean.setName("tom");
<!--CRLF-->
Birthday day = new Birthday("2010-11-22");<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
map.put("No.2", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
map.put("No.3", bean);//put<!--CRLF-->
<!--CRLF-->
failRed("==========XML >>> List===========");
<!--CRLF-->
List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));<!--CRLF-->
fail("size:" + studetns.size());//3<!--CRLF-->
for (Student s : studetns) {
<!--CRLF-->
fail(s.toString());<!--CRLF-->
}<!--CRLF-->
<!--CRLF-->
failRed("==========XML >>> Map===========");
<!--CRLF-->
Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));<!--CRLF-->
fail("size:" + maps.size());//3<!--CRLF-->
Set<String> key = maps.keySet();<!--CRLF-->
Iterator<String> iter = key.iterator();<!--CRLF-->
while (iter.hasNext()) {
<!--CRLF-->
String k = iter.next();<!--CRLF-->
fail(k + ":" + map.get(k));
<!--CRLF-->
}<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
e.printStackTrace();<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
-----------Xml >>> Bean--------------<!--CRLF-->
jack#1#china#2010-11-22#[email protected]<!--CRLF-->
==========XML >>> List===========<!--CRLF-->
size:3<!--CRLF-->
jack#1#china#2010-11-22#[email protected]<!--CRLF-->
tom#2#china#2010-11-22#[email protected]<!--CRLF-->
jack#0#null#null#null<!--CRLF-->
==========XML >>> Map===========<!--CRLF-->
size:3<!--CRLF-->
No.3:jack#0#null#null#null<!--CRLF-->
No.1:jack#1#china#2010-11-22#[email protected]<!--CRLF-->
No.2:tom#2#china#2010-11-22#[email protected]<!--CRLF-->
怎么样,成功的完成XML到JavaBean、List、Map的转换,更多对象转换还需要大家一一尝试。用法类似~这里就不一样赘述。
四、XStream对JSON的支持
xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar
1、 用JettisonMappedXmlDriver完成Java对象到JSON的转换
/**
<!--CRLF-->
* <b>function:</b>XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON
<!--CRLF-->
* 需要添加jettison jar
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:23:18 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeEntity2JETTSON() {<!--CRLF-->
failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString=========");
<!--CRLF-->
xstream = new XStream(new JettisonMappedXmlDriver());<!--CRLF-->
xstream.setMode(XStream.NO_REFERENCES);<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.toXML(bean));<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
=======JettisonMappedXmlDriver===JavaObject >>>> JaonString=========<!--CRLF-->
{"student":{"id":1,"name":"jack","email":"[email protected]","address":"china","birthday":[{},"2010-11-22"]}}<!--CRLF-->
JSON的转换和XML的转换用法一样,只是创建XStream需要传递一个参数,这个参数就是xml到JSON映射转换的驱动。这里会降到两个驱动,分别是JettisonMappedXmlDriver、JsonHierarchicalStreamDriver。
2、 JsonHierarchicalStreamDriver完成Java对象到JSON的转换
/**
<!--CRLF-->
* <b>function:</b>用XStream结合JsonHierarchicalStreamDriver驱动
<!--CRLF-->
* 转换java对象为JSON字符串
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:16:46 PM
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void writeEntiry2JSON() {<!--CRLF-->
failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");
<!--CRLF-->
xstream = new XStream(new JsonHierarchicalStreamDriver());<!--CRLF-->
//xstream.setMode(XStream.NO_REFERENCES);
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
failRed("-------Object >>>> JSON---------");
<!--CRLF-->
fail(xstream.toXML(bean));<!--CRLF-->
<!--CRLF-->
//failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
<!--CRLF-->
//删除根节点
<!--CRLF-->
xstream = new XStream(new JsonHierarchicalStreamDriver() {<!--CRLF-->
public HierarchicalStreamWriter createWriter(Writer out) {
<!--CRLF-->
return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);<!--CRLF-->
}<!--CRLF-->
});<!--CRLF-->
//xstream.setMode(XStream.NO_REFERENCES);
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.toXML(bean));<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========<!--CRLF-->
-------Object >>>> JSON---------<!--CRLF-->
{"student": {
<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
}}<!--CRLF-->
{<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,你可以重写createWriter方法,删掉根节点。
看上面的结果,一个是默认带根节点的JSON对象,它只是将类名作为一个属性,将对象作为该属性的一个值。而另一个没有带根属性的JSON就是通过重写createWriter方法完成的。
3、 将List集合转换成JSON字符串
@Test<!--CRLF-->
public void writeList2JSON() {<!--CRLF-->
failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========");
<!--CRLF-->
JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();
<!--CRLF-->
xstream = new XStream(driver);
<!--CRLF-->
//xstream = new XStream(new JettisonMappedXmlDriver());//转换错误
<!--CRLF-->
//xstream.setMode(XStream.NO_REFERENCES);
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
<!--CRLF-->
List<Student> list = new ArrayList<Student>();
<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(2);<!--CRLF-->
bean.setName("tom");
<!--CRLF-->
Birthday day = new Birthday("2010-11-22");<!--CRLF-->
bean.setBirthday(day);<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
list.add(bean);//add
<!--CRLF-->
<!--CRLF-->
fail(xstream.toXML(list));<!--CRLF-->
<!--CRLF-->
//failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
<!--CRLF-->
//删除根节点
<!--CRLF-->
xstream = new XStream(new JsonHierarchicalStreamDriver() {<!--CRLF-->
public HierarchicalStreamWriter createWriter(Writer out) {
<!--CRLF-->
return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);<!--CRLF-->
}<!--CRLF-->
});<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.toXML(list));<!--CRLF-->
}<!--CRLF-->
运行后结果如下
======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========<!--CRLF-->
##{"list": [
<!--CRLF-->
{<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
},<!--CRLF-->
{<!--CRLF-->
"id": 2,
<!--CRLF-->
"name": "tom",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
},<!--CRLF-->
{<!--CRLF-->
"id": 0,
<!--CRLF-->
"name": "jack"<!--CRLF-->
}<!--CRLF-->
]}<!--CRLF-->
#[<!--CRLF-->
{<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
},<!--CRLF-->
{<!--CRLF-->
"id": 2,
<!--CRLF-->
"name": "tom",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
},<!--CRLF-->
{<!--CRLF-->
"id": 0,
<!--CRLF-->
"name": "jack"<!--CRLF-->
}<!--CRLF-->
]<!--CRLF-->
上面的list1是使用JsonHierarchicalStreamDriver 转换的,当然你也可以使用JettisonMappedXmlDriver驱动进行转换;用JettisonMappedXmlDriver转换后,你会发现格式不同而且没有根属性。
4、 Map转换json
@Test<!--CRLF-->
public void writeMap2JSON() {<!--CRLF-->
failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========");
<!--CRLF-->
xstream = new XStream(new JsonHierarchicalStreamDriver());<!--CRLF-->
//xstream = new XStream(new JettisonMappedXmlDriver());
<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
<!--CRLF-->
Map<String, Student> map = new HashMap<String, Student>();
<!--CRLF-->
map.put("No.1", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setAddress("china");
<!--CRLF-->
bean.setEmail("[email protected]");
<!--CRLF-->
bean.setId(2);<!--CRLF-->
bean.setName("tom");
<!--CRLF-->
bean.setBirthday(new Birthday("2010-11-21"));<!--CRLF-->
map.put("No.2", bean);//put<!--CRLF-->
<!--CRLF-->
bean = new Student();
<!--CRLF-->
bean.setName("jack");
<!--CRLF-->
map.put("No.3", bean);//put<!--CRLF-->
<!--CRLF-->
fail(xstream.toXML(map));<!--CRLF-->
<!--CRLF-->
//failRed("========JsonHierarchicalStreamDriver==删除根节点=========");
<!--CRLF-->
//删除根节点
<!--CRLF-->
xstream = new XStream(new JsonHierarchicalStreamDriver() {<!--CRLF-->
public HierarchicalStreamWriter createWriter(Writer out) {
<!--CRLF-->
return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);<!--CRLF-->
}<!--CRLF-->
});<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.toXML(map));<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
======JsonHierarchicalStreamDriver==== Map >>>> JaonString=========<!--CRLF-->
{"map": [
<!--CRLF-->
[<!--CRLF-->
"No.3",
<!--CRLF-->
{<!--CRLF-->
"id": 0,
<!--CRLF-->
"name": "jack"<!--CRLF-->
}<!--CRLF-->
],<!--CRLF-->
[<!--CRLF-->
"No.1",
<!--CRLF-->
{<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
],<!--CRLF-->
[<!--CRLF-->
"No.2",
<!--CRLF-->
{<!--CRLF-->
"id": 2,
<!--CRLF-->
"name": "tom",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-21"<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
]<!--CRLF-->
]}<!--CRLF-->
[<!--CRLF-->
[<!--CRLF-->
"No.3",
<!--CRLF-->
{<!--CRLF-->
"id": 0,
<!--CRLF-->
"name": "jack"<!--CRLF-->
}<!--CRLF-->
],<!--CRLF-->
[<!--CRLF-->
"No.1",
<!--CRLF-->
{<!--CRLF-->
"id": 1,
<!--CRLF-->
"name": "jack",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-22"<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
],<!--CRLF-->
[<!--CRLF-->
"No.2",
<!--CRLF-->
{<!--CRLF-->
"id": 2,
<!--CRLF-->
"name": "tom",<!--CRLF-->
"email": "[email protected]",<!--CRLF-->
"address": "china",<!--CRLF-->
"birthday": {
<!--CRLF-->
"birthday": "2010-11-21"<!--CRLF-->
}<!--CRLF-->
}<!--CRLF-->
]<!--CRLF-->
]<!--CRLF-->
5、 将JSON转换java对象
/**
<!--CRLF-->
* <b>function:</b>JsonHierarchicalStreamDriver可以将简单的json字符串转换成java对象,list、map转换不成功;
<!--CRLF-->
* JsonHierarchicalStreamDriver读取JSON字符串到java对象出错
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate Nov 27, 2010 1:22:26 PM
<!--CRLF-->
* @throws JSONException
<!--CRLF-->
*/
<!--CRLF-->
@Test<!--CRLF-->
public void readJSON2Object() throws JSONException {<!--CRLF-->
String json = "{\"student\": {" +
<!--CRLF-->
"\"id\": 1," +
<!--CRLF-->
"\"name\": \"haha\"," +
<!--CRLF-->
"\"email\": \"email\"," +
<!--CRLF-->
"\"address\": \"address\"," +
<!--CRLF-->
"\"birthday\": {" +
<!--CRLF-->
"\"birthday\": \"2010-11-22\"" +
<!--CRLF-->
"}" +
<!--CRLF-->
"}}";
<!--CRLF-->
//JsonHierarchicalStreamDriver读取JSON字符串到java对象出错,但JettisonMappedXmlDriver可以
<!--CRLF-->
xstream = new XStream(new JettisonMappedXmlDriver());<!--CRLF-->
xstream.alias("student", Student.class);<!--CRLF-->
fail(xstream.fromXML(json).toString());<!--CRLF-->
<!--CRLF-->
//JettisonMappedXmlDriver转换List集合出错,但JsonHierarchicalStreamDriver可以转换正确
<!--CRLF-->
//JettisonMappedXmlDriver 转换的字符串 {"list":{"student":[{"id":1,"name":"haha","email":"email","address":"address","birthday":[{},"2010-11-22"]}]},"student":{"id":2,"name":"tom","email":"[email protected]","address":"china","birthday":[{},"2010-11-22"]}}
<!--CRLF-->
json = "{\"list\": [{" +
<!--CRLF-->
"\"id\": 1," +
<!--CRLF-->
"\"name\": \"haha\"," +
<!--CRLF-->
"\"email\": \"email\"," +
<!--CRLF-->
"\"address\": \"address\"," +
<!--CRLF-->
"\"birthday\": {" +
<!--CRLF-->
"\"birthday\": \"2010-11-22\"" +
<!--CRLF-->
"}" +
<!--CRLF-->
"},{" +
<!--CRLF-->
"\"id\": 2," +
<!--CRLF-->
"\"name\": \"tom\"," +
<!--CRLF-->
"\"email\": \"[email protected]\"," +
<!--CRLF-->
"\"address\": \"china\"," +
<!--CRLF-->
"\"birthday\": {" +
<!--CRLF-->
"\"birthday\": \"2010-11-22\"" +
<!--CRLF-->
"}" +
<!--CRLF-->
"}]}";
<!--CRLF-->
System.out.println(json);//用js转换成功
<!--CRLF-->
List list = (List) xstream.fromXML(json);<!--CRLF-->
System.out.println(list.size());//0好像转换失败
<!--CRLF-->
}<!--CRLF-->
运行后结果如下:
haha#1#address#2010-11-22#email<!--CRLF-->
{"list": [{"id": 1,"name": "haha","email": "email","address": "address","birthday": {"birthday": "2010-11-22"}},<!--CRLF-->
{"id": 2,"name": "tom","email": "[email protected]","address": "china","birthday": {"birthday": "2010-11-22"}}]}<!--CRLF-->
0<!--CRLF-->