我有一个像这样的简单班级

    import nl.hu.pf.coproco.model.Observeable;

    @XmlRootElement (name = "Purpose")
    @XmlAccessorType (XmlAccessType.FIELD)
    public class Purpose implements Observeable{
        private String name;
        private ArrayList<Observer> observers;

        @XmlElement (name = "subPurpose")
        private ArrayList<Purpose> subPurposes;

        //methods
    }


但是Observable是一个接口,所以我得到了一个例外,因为JAXB无法处理接口。我试图弄清楚如何使用ArrayList<Observer>忽略该字段,以免将其导出到xml。

我尝试使用@XmlTransient批注,但是我收到以下信息javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"purpose"). Expected elements are <{}Purpose>

取消编组但我也想编组该类时发生这种情况

样本XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purpose>
    <name>All Purposes</name>
    <subPurpose>
        <name>Creational</name>
    </subPurpose>
    <subPurpose>
        <name>Structural</name>
    </subPurpose>
    <subPurpose>
        <name>Behavioral</name>
        <subPurpose>
            <name>Behavioral 1</name>
        </subPurpose>
        <subPurpose>
            <name>Behavioral 2</name>
        </subPurpose>
    </subPurpose>
</purpose>


接口Observable如下所示:

public interface Observeable {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers(Object o, String arg);
}

最佳答案

您的xml包含purpose而不是Purpose,因此将@XmlRootElement(name = "Purpose")更改为

@XmlRootElement(name = "purpose")


并在这样的观察者上添加@XmlTransient

@XmlTransient
private ArrayList<Observer> observers;

10-05 17:50