简体   繁体   中英

Spring + JAXB - Unmarshal XML with the same element root

I am using RestTemplate to call 2 different Rest APIs that return the following XML:

<response><user>...</user></response>
<response><client>...</client></response>

In my application I have 2 classes:

@XmlRootElement(name = "response")
class UserResponse {...}

@XmlRootElement(name = "response")
class ClientResponse {...}

I don't have control over the APIs, I can't modify the response XML.

How can I work with 2 different responses and the same Root Element?

Thanks.

You could instead have one Response class which would contain a User and a Client class, which would be elements contained in the response root element instead. Something like that:

@XmlRootElement(name = "response")
@XmlAccessorType(XmlAccessType.FIELD)
class Response {
    @XmlElement(required = false)
    private User user;
    @XmlElement(required = false)
    private Client client;
}

class User {
}

class Client {
}

如果知道期望的响应类型,则可以不使用@XmlRootElement批注,而使用采用Class参数的解组方法之一。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM