日期:2014-05-16 浏览次数:20431 次
package edu.jlu.fuliang; public class Person { private String name; private int age; private Address address; private String email; public Person() { } public Person( String name, int age, Address address, String email ) { this.name = name; this.age = age; this.address = address; this.email = email; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public int getAge() { return age; } public void setAge( int age ) { this.age = age; } public Address getAddress() { return address; } public void setAddress( Address address ) { this.address = address; } public String getEmail() { return email; } public void setEmail( String email ) { this.email = email; } @Override public String toString() { return "name:" + name + ",age:" + age + ",address:" + address + ",email:" + email; } }
package edu.jlu.fuliang; public class Address { private String street; private String city; public Address() { } public Address( String street, String city ) { this.street = street; this.city = city; } public String getStreet() { return street; } public void setStreet( String street ) { this.street = street; } public String getCity() { return city; } public void setCity( String city ) { this.city = city; } @Override public String toString() { return "street:" + street + ",city:" + city; } }
package edu.jlu.fuliang; import junit.framework.TestCase; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; public class XStreamTest extends TestCase { private Person person; @Override protected void setUp() throws Exception { Address address = new Address("中关村","北京"); person = new Person("张三",12,address,"zhangsan@gmail.com"); } public void testObjectXML() { XStream xStream = new XStream(); xStream.alias( "Person", Person.class); xStream.alias( "Address", Address.class ); String xml = xStream.toXML( person ); System.out.println("Serialize person to XML:\n" + xml); Person p = (Person) xStream.fromXML( xml ); System.out.println("Deserialize XML to person:\n" + p); } public void testObjectJSON(){ XStream xStream = new XStream(new JettisonMappedXmlDriver()); xStream.setMode( XStream.NO_REFERENCES ); xStream.alias( "Person", Person.class ); xStream.alias("Address", Address.class); String json = xStream.toXML( person ); System.out.println("Serialize person to JSON:\n" + json); Person p = (Person) xStream.fromXML( json ); System.out.println("Deserialize JSON to person:\n" + p); } }