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