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