亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

java xstream如何映射復雜對象

小樊
86
2024-07-21 14:52:02
欄目: 編程語言

在使用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 + '\'' +
                '}';
    }
}

在這個示例中,我們定義了兩個類PersonAddress,并使用XStream進行對象映射。通過定義別名和字段映射,我們可以將復雜對象序列化為XML,并將XML反序列化為復雜對象。

0
五大连池市| 石楼县| 巴林右旗| 三亚市| 分宜县| 苍南县| 宝鸡市| 阳新县| 宁明县| 鱼台县| 贵阳市| 上高县| 伊金霍洛旗| 托里县| 阳山县| 大城县| 毕节市| 海伦市| 黔东| 龙南县| 西和县| 沅陵县| 克拉玛依市| 布拖县| 花莲市| 通化市| 齐河县| 清新县| 三穗县| 迭部县| 深水埗区| 景宁| 印江| 丹寨县| 广安市| 巩留县| 宜宾县| 邓州市| 兴安盟| 峨眉山市| 浠水县|