在使用Java XStream进行对象映射时,可以通过定义不同的别名和映射规则来处理复杂对象的映射。以下是一个示例,演示了如何映射一个包含多个属性和对象的复杂对象:
import com.thoughtworks.xstream.XStream;
public class Main {
public static void main(String[] args) {
XStream xstream = new XStream();
// 定义别名
xstream.alias("person", Person.class);
xstream.alias("address", Address.class);
// 添加字段映射
xstream.aliasField("firstName", Person.class, "firstName");
xstream.aliasField("lastName", Person.class, "lastName");
xstream.aliasField("street", Address.class, "street");
xstream.aliasField("city", Address.class, "city");
xstream.aliasField("zipCode", Address.class, "zipCode");
// 创建一个复杂对象
Person person = new Person("John", "Doe");
Address address = new Address("123 Main St", "Anytown", "12345");
person.setAddress(address);
// 将复杂对象序列化为XML
String xml = xstream.toXML(person);
System.out.println(xml);
// 将XML反序列化为复杂对象
Person person2 = (Person) xstream.fromXML(xml);
System.out.println(person2);
}
}
class Person {
private String firstName;
private String lastName;
private Address address;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", address=" + address +
'}';
}
}
class Address {
private String street;
private String city;
private String zipCode;
public Address(String street, String city, String zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
@Override
public String toString() {
return "Address{" +
"street='" + street + '\'' +
", city='" + city + '\'' +
", zipCode='" + zipCode + '\'' +
'}';
}
}
在这个示例中,我们定义了两个类Person
和Address
,并使用XStream进行对象映射。通过定义别名和字段映射,我们可以将复杂对象序列化为XML,并将XML反序列化为复杂对象。