使用超类XMLRootElement名称值的JAXB带注释的子类

时间:2012-11-22 08:08:57

标签: java jaxb

我正在使用JAXB 2.1,我对我看到的XML输出感到困惑。下面我有两个扩展同一父级的子类。当使用REST在浏览器中编组并查看为XML时,Child类1(GeoLocationDecodedPayload)始终具有 geoLocationDecodedPayload 的根元素。由于某种原因,子类2(AltitudeDecodedPayload) altitudeDecodedPayload 作为其根元素,这是其在@XMLRootElement注释中指定的意外情况。 XML输出显示 geoPayload 的超类(GeoPayload)@XMLRootElement。任何想法为什么这两个阶段的行为不同?

儿童班1:

package com.api.model.vo.decoder;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.api.util.decoder.DecoderConstants;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "geoLocationDecodedPayload")
public class GeoLocationDecodedPayload extends GeoPayload implements Serializable {

   public GeoLocationDecodedPayload() {}

}

儿童班2:

package com.api.model.vo.decoder;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.api.util.decoder.DecoderConstants;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "altitudeDecodedPayload")
public class AltitudeDecodedPayload extends GeoPayload implements Serializable {

    public AltitudeDecodedPayload() {}

}

家长班:

package com.api.model.vo.decoder;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "geoPayload")
public class GeoPayload {

    public GeoPayload() {}
}

1 个答案:

答案 0 :(得分:1)

我忘了在下面包含AltitudeDecodedPayload.class。这解决了我的问题。

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="payloadResponse")
public class PayloadResponse extends AbstractResponse{
    @XmlElementWrapper(name="decodedPayloads")
    @XmlElementRefs({
        @XmlElementRef(type=GeoPayload.class),
        @XmlElementRef(type=GeoLocationDecodedPayload .class),
        @XmlElementRef(type=AltitudeDecodedPayload .class)