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://download.csdn.net/detail/u013791374/9636008官方的示例很全,官方参考示例:http://xstream.codehaus.org/tutorial.html添加xstream-1.3.1.jar文件到工程中,就可以开始下面的工作;2、 测试用例代码 import com.thoughtworks.xstream.XStream;
/**
* @author zwj
*
* 2016-9-21下午3:09:53
* XStream java转换xml
*/
public class XStreamTest {
public static void main(String[] args) {
System.out.println(setBean());
}
public static String setBean(){
Student sdt = new Student();
sdt.setId(1);
sdt.setName("张无忌");
sdt.setEmail("zhangwuji@sina.com");
sdt.setAddress("www.baidu.com");
return beanToXml(sdt);
}
public static String beanToXml(Student sdt){
XStream xst = new XStream();
xst.alias("xml", sdt.getClass());//设置别名
return xst.toXML(sdt);//将对象转换成xml
}
}
通过XStream对象的toXML方法就可以完成Java对象到XML的转换,toXML方法还有2个相同签名的方法,需要传递一个流。然后通过流来完成xml信息的输出。3、 需要的JavaBean package com.hoo.entity; package com.cn.test.objecttoxml;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class Student {
private int id;
private String name;
private String email;
private String address;
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
//getter、setter
}
运行后结果如下: ------------Bean->XML------------<xml>
<id>1</id>
<name>张无忌</name>
<email>zhangwuji@sina.com</email>
<address>皖六安</address>
< /xml> 2、 将List集合转换成xml文档 /** * <b>function:</b>将Java的List集合转换成XML对象 * @author hoojo * @createDate Nov 27, 2010 12:20:07 PM */ public static void main(String[] args) { System.out.println(setBean()); } public static String setBean(){ List<Student> list = new ArrayList<Student>(); Student sd = new Student(); sd.setId(1); sd.setName("张无忌"); sd.setEmail("zhangwuji@sina.com"); sd.setAddress("皖六安"); list.add(sd); Student sd2 = new Student(); sd2.setId(1); sd2.setName("张无忌2"); sd2.setEmail("zhangwuji@sina.com2"); sd2.setAddress("皖六安2"); list.add(sd2); return beanToXml(list); } public static String beanToXml(Object obj){ XStream xst = new XStream(); //xstream list转xml 设置<list>标签别名 xstream.alias("xxx", List.class); xst.alias("xml",List.class); //aliasPackage 设置包别名 xst.aliasPackage("list", "com.cn.test.objecttoxml"); return xst.toXML(obj); } 上面的代码运行后,结果如下: ----------List-->XML----------<xml>
<list.Student>
<id>1</id>
<name>张无忌</name>
<email>zhangwuji@sina.com</email>
<address>皖六安</address>
</list.Student>
<list.Student>
<id>1</id>
<name>张无忌2</name>
<email>zhangwuji@sina.com2</email>
<address>皖六安2</address>
</list.Student>
< /xml> 如果不加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、 Map集合转换xml文档 /** * <b>function:</b>Java Map集合转XML * @author hoojo * @createDate Nov 27, 2010 1:13:26 PM */@Testpublic void writeMap2XML() { try { Map<String,Student> map = new HashMap<String,Student>();
Student sd = new Student();
sd.setId(1);
sd.setName("张无忌");
sd.setEmail("zhangwuji@sina.com");
sd.setAddress("皖六安");
map.put("No.1", sd);
Student sd2 = new Student();
sd2.setId(2);
sd2.setName("张无忌2");
sd2.setEmail("zhangwuji@sina.com2");
sd2.setAddress("皖六安2");
map.put("No.2", sd2);
return beanToXml(map) } catch (Exception e) { e.printStackTrace(); }}public static String beanToXml(Object obj){ XStream xst = new XStream(); //不需要设置MAP.CLASS //xst.alias("xml",Map.class); xst.alias("student", Student.class); xst.alias("key", String.class); xst.useAttributeFor(Student.class, "id"); //aliasPackage 设置包别名 return xst.toXML(obj); }运行后结果如下: ---------Map --> XML---------<map>
<entry>
<key>No.1</key>
<student id="1">
<name>张无忌</name>
<email>zhangwuji@sina.com</email>
<address>皖六安</address>
</student>
</entry>
<entry>
<key>No.2</key>
<student id="2">
<name>张无忌2</name>
<email>zhangwuji@sina.com2</email>
<address>皖六安2</address>
</student>
</entry>
< /map>
5、 用OutStream输出流写XML /** * <b>function:</b>用OutStream输出流写XML * @author hoojo * @createDate Nov 27, 2010 1:13:48 PM */@Testpublic void writeXML4OutStream() { try { out = xstream.createObjectOutputStream(System.out); Student stu = new Student(); stu.setName("jack"); Classes c = new Classes("一班", bean, stu); c.setNumber(2); failRed("---------ObjectOutputStream # JavaObject--> XML---------"); out.writeObject(stu); out.writeObject(new Birthday("2010-05-33")); out.write(22);//byte out.writeBoolean(true); out.writeFloat(22.f); out.writeUTF("hello"); } catch (Exception e) { e.printStackTrace(); }}使用输出流后,可以通过流对象完成xml的构建,即使没有JavaBean对象,你可以用流来构建一个复杂的xml文档,运行后结果如下: ---------ObjectOutputStream # JavaObject--> XML---------<object-stream> <com.hoo.entity.Student> <id>0</id> <name>jack</name> </com.hoo.entity.Student> <com.hoo.entity.Birthday> <birthday>2010-05-33</birthday> </com.hoo.entity.Birthday> <byte>22</byte> <boolean>true</boolean> <float>22.0</float> <string>hello</string></object-stream>三、XML内容转换Java对象
1、 将xml文档转换成Java对象 /** * <b>function:</b>将XML字符串转换成Java对象 * @author hoojo * @createDate Nov 27, 2010 2:39:06 PM */@Testpublic void readXml2Object() { try { Student sd = new Student(); sd.setId(1); sd.setName("张无忌"); sd.setEmail("zhangwuji@sina.com"); sd.setAddress("皖六安"); xst.alias("xml",obj.getClass()); String xmlStr = xst.toXML(obj); System.out.println("java对象转xml:"+xmlStr); Student sdt = (Student)xst.fromXML(xmlStr); System.out.println("对象转换xml方法:"+sdt.toString()); } catch (Exception e) { e.printStackTrace(); }}运行后结果如下: -----------Xml >>> Bean--------------java对象转xml:<xml> <id>1</id> <name>张无忌</name> <email>zhangwuji@sina.com</email> <address>皖六安</address></xml>对象转换xml方法:Student[id=1,name=张无忌,email=zhangwuji@sina.com,address=皖六安] 怎么样,成功的完成XML到JavaBean、List、Map的转换,更多对象转换还需要大家一一尝试。用法类似~这里就不一样赘述。 四、XStream对JSON的支持 xStream对JSON也有非常好的支持,它提供了2个模型驱动。用这2个驱动可以完成Java对象到JSON的相互转换。使用JettisonMappedXmlDriver驱动,将Java对象转换成json,需要添加jettison.jar1、 用JettisonMappedXmlDriver完成Java对象到JSON的转换 /** * <b>function:</b>XStream结合JettisonMappedXmlDriver驱动,转换Java对象到JSON * 需要添加jettison jar * @author hoojo * @createDate Nov 27, 2010 1:23:18 PM */@Testpublic void writeEntity2JETTSON() { failRed("=======JettisonMappedXmlDriver===JavaObject >>>> JaonString========="); xstream = new XStream(new JettisonMappedXmlDriver()); xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student", Student.class); fail(xstream.toXML(bean));}运行后结果如下: =======JettisonMappedXmlDriver===JavaObject >>>> JaonString========={"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的转换 /** * <b>function:</b>用XStream结合JsonHierarchicalStreamDriver驱动 * 转换java对象为JSON字符串 * @author hoojo * @createDate Nov 27, 2010 1:16:46 PM */@Testpublic void writeEntiry2JSON() { failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); xstream = new XStream(new JsonHierarchicalStreamDriver()); //xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student", Student.class); failRed("-------Object >>>> JSON---------"); fail(xstream.toXML(bean)); //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); //删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); } }); //xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student", Student.class); fail(xstream.toXML(bean));}运行后结果如下: ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========-------Object >>>> JSON---------{"student": { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" }}}{ "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" }}使用JsonHierarchicalStreamDriver转换默认会给转换后的对象添加一个根节点,但是在构建JsonHierarchicalStreamDriver驱动的时候,你可以重写createWriter方法,删掉根节点。看上面的结果,一个是默认带根节点的JSON对象,它只是将类名作为一个属性,将对象作为该属性的一个值。而另一个没有带根属性的JSON就是通过重写createWriter方法完成的。3、 将List集合转换成JSON字符串 @Testpublic void writeList2JSON() { failRed("======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString========="); JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver(); xstream = new XStream(driver); //xstream = new XStream(new JettisonMappedXmlDriver());//转换错误 //xstream.setMode(XStream.NO_REFERENCES); xstream.alias("student", Student.class); List<Student> list = new ArrayList<Student>(); list.add(bean);//add bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); Birthday day = new Birthday("2010-11-22"); bean.setBirthday(day); list.add(bean);//add bean = new Student(); bean.setName("jack"); list.add(bean);//add fail(xstream.toXML(list)); //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); //删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); } }); xstream.alias("student", Student.class); fail(xstream.toXML(list));}运行后结果如下 ======JsonHierarchicalStreamDriver====JavaObject >>>> JaonString=========##{"list": [ { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 0, "name": "jack" }]}#[ { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-22" } }, { "id": 0, "name": "jack" }]上面的list1是使用JsonHierarchicalStreamDriver 转换的,当然你也可以使用JettisonMappedXmlDriver驱动进行转换;用JettisonMappedXmlDriver转换后,你会发现格式不同而且没有根属性。4、 Map转换json @Testpublic void writeMap2JSON() { failRed("======JsonHierarchicalStreamDriver==== Map >>>> JaonString========="); xstream = new XStream(new JsonHierarchicalStreamDriver()); //xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("student", Student.class); Map<String, Student> map = new HashMap<String, Student>(); map.put("No.1", bean);//put bean = new Student(); bean.setAddress("china"); bean.setEmail("tom@125.com"); bean.setId(2); bean.setName("tom"); bean.setBirthday(new Birthday("2010-11-21")); map.put("No.2", bean);//put bean = new Student(); bean.setName("jack"); map.put("No.3", bean);//put fail(xstream.toXML(map)); //failRed("========JsonHierarchicalStreamDriver==删除根节点========="); //删除根节点 xstream = new XStream(new JsonHierarchicalStreamDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); } }); xstream.alias("student", Student.class); fail(xstream.toXML(map));}运行后结果如下: ======JsonHierarchicalStreamDriver==== Map >>>> JaonString========={"map": [ [ "No.3", { "id": 0, "name": "jack" } ], [ "No.1", { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } } ], [ "No.2", { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-21" } } ]]}[ [ "No.3", { "id": 0, "name": "jack" } ], [ "No.1", { "id": 1, "name": "jack", "email": "jack@email.com", "address": "china", "birthday": { "birthday": "2010-11-22" } } ], [ "No.2", { "id": 2, "name": "tom", "email": "tom@125.com", "address": "china", "birthday": { "birthday": "2010-11-21" } } ]]5、 将JSON转换java对象 /** * <b>function:</b>JsonHierarchicalStreamDriver可以将简单的json字符串转换成java对象,list、map转换不成功; * JsonHierarchicalStreamDriver读取JSON字符串到java对象出错 * @author hoojo * @createDate Nov 27, 2010 1:22:26 PM * @throws JSONException */@Testpublic void readJSON2Object() throws JSONException { String json = "{\"student\": {" + "\"id\": 1," + "\"name\": \"haha\"," + "\"email\": \"email\"," + "\"address\": \"address\"," + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "}}"; //JsonHierarchicalStreamDriver读取JSON字符串到java对象出错,但JettisonMappedXmlDriver可以 xstream = new XStream(new JettisonMappedXmlDriver()); xstream.alias("student", Student.class); fail(xstream.fromXML(json).toString()); //JettisonMappedXmlDriver转换List集合出错,但JsonHierarchicalStreamDriver可以转换正确 //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"]}} json = "{\"list\": [{" + "\"id\": 1," + "\"name\": \"haha\"," + "\"email\": \"email\"," + "\"address\": \"address\"," + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "},{" + "\"id\": 2," + "\"name\": \"tom\"," + "\"email\": \"tom@125.com\"," + "\"address\": \"china\"," + "\"birthday\": {" + "\"birthday\": \"2010-11-22\"" + "}" + "}]}"; System.out.println(json);//用js转换成功 List list = (List) xstream.fromXML(json); System.out.println(list.size());//0好像转换失败}运行后结果如下: haha#1#address#2010-11-22#email{"list": [{"id": 1,"name": "haha","email": "email","address": "address","birthday": {"birthday": "2010-11-22"}},{"id": 2,"name": "tom","email": "tom@125.com","address": "china","birthday": {"birthday": "2010-11-22"}}]}0JSON到Java的转换是fromXML方法。 |
|