SimpleXML Java 添加 class 作为元素

SimpleXML Java add class as element

在我的 Android 项目中,我有两个 XML 文件,如下所示:

<request>
  <target>www.facebook.com</target>
  <packetsize>32</packetsize>
  <timeout>4</timeout>
  ...
</request>

<response>
  <target>www.facebook.com</target>
  <packetsize>32</packetsize>
  <timeout>4</timeout>
  ...
</request>

两个文件具有相同的元素,但根节点不同。使用 SimpleXML 框架,我想创建一个名为 PinResponse 的新 class 作为 XML 文件中所有元素的容器,用于 reusing/changing 响应的属性。为此,我想在我的 XML 模型 classes 中引用 class 作为元素。

PinResponse class:

@Element
public class PinResponse {

    @Element(name = "target")
    private String target;

    @Element(name = "packetsize")
    private int packetSize;

    @Element(name = "timeout")
    private int timeout;

    ...
}

XML 型号 class:

@Root(name = "request")
public class PingResponseData {

    @Element
    private PinResponse pinResponse;

    public PinResponse getPinResponse() {
        return pinResponse;
    }
}

但我总是得到 ElementException:

org.simpleframework.xml.core.ElementException: Element 'target' does not have a match in class

如何将 PinResponse class 作为元素添加到我的 XML 模型 classes?

通常情况下,你会这样做:

public abstract class PingRequestResponse {

    @Element(name = "target")
    private String target;

    @Element(name = "packetsize")
    private int packetSize;

    @Element(name = "timeout")
    private int timeout;

    ...
}

@Root(name = "request")
public class PingRequest extends PingRequestResponse { }

@Root(name = "response")
public class PingResponse extends PingRequestResponse { }

但是,我对 SimpleXML 的使用还不够多,无法知道注释是否会在这样的子类中正常工作。

试一试,看看会发生什么。

Kris Larsons 帮助我解决了我的问题,这就是我现在的最终解决方案:

Base class: (受保护访问使用 subclass 中的元素)

public abstract class Ping {

    @Element(name = "target")
    protected String target;

    @Element(name = "packetsize")
    protected int packetSize;

    @Element(name = "timeout")
    protected int timeout;

    ...(getter/setter)
}

请求子class:

@Root(name = "request")
public class PingRequest extends PingRequestResponse { 

    public PingRequest(Ping ping) {
            this.target = ping.getTarget();
            this.packetsize = ping.getPacketsize();
            this.timeout = ping.getTimeout();
            ...
}

回复子class:

@Root(name = "response")
public class PingResponse extends PingRequestResponse { 
            //empty as it has the same elements, if it would have additional fields, they would be added here
}