XStream 轻松搞定JAVA对象与XML/JSON之间相互转换
上一遍已对xstream进行了初步认识,此处就不再多作介绍,直入主题,以下主要主要为,JavaBean --> XML / JSON 、XML / JSON --> JavaBean之间相互转换:
一| 先写实体类:
Address.java
import java.io.PrintWriter;import vo.Address;import vo.Person;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;import com.thoughtworks.xstream.io.xml.DomDriver;/** *@class Description: *@author like *@version create on May 19, 2011 */public class Test {public static void main(String[] args) { //JavaBean --> XMLAddress address=new Address();Person person=new Person();address.setOldAddress("湖南长沙");address.setNewAddress("广州白云");person.setName("理科");person.setSex("男");person.setAge(22);person.setAddress(address);XStream xstream = new XStream(new DomDriver());xstream.alias("person", Person.class);xstream.alias("address", Address.class);xstream.toXML(person,new PrintWriter(System.out)); //XML --> JavaBeanString strxml="<person><name>理科</name><sex>男</sex><age>19</age><address><oldAddress>湖南长沙</oldAddress><newAddress>广州白云</newAddress></address></person>";XStream xstream2 = new XStream(new DomDriver());xstream2.alias("person", Person.class);xstream2.alias("address", Address.class);Person person2=(Person) xstream2.fromXML(strxml);System.out.println(person2.getName());System.out.println(person2.getSex());System.out.println(person2.getAddress().getOldAddress());System.out.println(person2.getAddress().getNewAddress()); //JavaBean --> JSONAddress address3=new Address();Person person3=new Person();address3.setOldAddress("湖南长沙");address3.setNewAddress("广州白云");person3.setName("理科");person3.setSex("男");person3.setAge(22);person3.setAddress(address3); //new JsonHierarchicalStreamDriver()XStream xstream3 = new XStream(new JsonHierarchicalStreamDriver());xstream3.alias("person", Person.class);xstream3.alias("address", Address.class);//new PrintWriter(System.out) 输出去控制台xstream3.toXML(person3,new PrintWriter(System.out)); //JSON--> JavaBeanString jsonstr="{"person": {"name": "理科","sex": "男","age": "19","address": {"oldAddress": "湖南长沙","newAddress": "广州白云"}}}"; //new JettisonMappedXmlDriver()XStream xstream4 = new XStream(new JettisonMappedXmlDriver());xstream4.alias("person", Person.class);xstream4.alias("address", Address.class);Person person4=(Person) xstream4.fromXML(jsonstr);System.out.println(person4.getName());System.out.println(person4.getSex());System.out.println(person4.getAddress().getOldAddress());System.out.println(person4.getAddress().getNewAddress());}}