0

我有这种 xml 格式作为不同 http 请求的输出。

<transaction>
<respmsg>...</respmsg>
<respcode>0000</respcode>
<status>success</status>
</transaction>

下面是我的交易类表示

@root
class Transaction {
   @Element
   public ResponseMessage respmsg;
   @Element
   public int respcode;
   @Element
   public String status;
}

“respmsg”属性的抽象类表示

abstract class ResponseMessage {

}

这很容易映射到 Class 对象。然而,“respmsg”对于登录请求的每个请求都是不同的,respmsg 可能是

<respmsg>
   <firstname>John</firstname>
   <lastname>Doe</lastname>
   <mobilephone>1234</mobilephone>
   <email>johndoe@test.com</email>
</respmsg>


class LoginResponseMessage extends ResponseMessage {
    @Element
    public String firstname;

    @Element
    public String lastname;

    @Element
    public String mobilephone;

    @Element
    public String email;
}

对于位置请求,它可能是

<respmsg>
   <address1>121 121 UAE Bldg, dubai</address1>
   <address2/>
   <city>Dubai</city>
   <postalcode>121</postalcode>
   <region>dubai</region>
</respmsg>

class LocationResponseMessage extends ResponseMessage {
    @Element
    public String address1;

    @Element
    public String address2;

    @Element
    public String postalcode;

    @Element
    public String region;
}

如何设计我的类,以便它知道在反序列化期间用于 respmsg 的类类型?

String xmlData = retrieve(urls[0]); //retrieve fetches the string xml from the http request
Serializer serializer = new Persister();
Reader reader = new StringReader(xmlData);
Transaction t = serializer.read(Transaction.class, reader, false);
4

1 回答 1

0

根据要求,发布我的评论作为答案:


<respmsg>给标签添加一个属性来说明它是哪种类型呢?

例如:

<respmsg type="LocationResponseMessage">
于 2013-10-31T17:18:31.790 回答