How to use RestTemplate with multiple response types?

Viewed 16635

I'm using spring RestTemplate for communication with a xml webservice backend as follows:

ResponseEntity<MainDTO> dto = restTemplate.postForObject(url, postData, MainDTO.class);

Problem: the backend might either respond with MainDTO for normal data or with ErrorDTO in case of failures. But both with HTTP 200.

But I don't know which object will come back before! Anyways restTemplate requires me to pass the class type before.

So, how could I parse the xml either to normal or the error bean?

Sidenote: I don't have any control of the webservice backend.

6 Answers

I had the same problem, I solved it like this:

I created a Response class and inside I put the two response objects. I have noted all three classes with

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)

ResponseEntity <Response> responseEntity = restTemplate.postForEntity (url, request, Response.class);
Object res = responseEntity.getBody ();

if (res! = null) {
    if (res instanceof MainDTO) {
        ...
    } else if (res instanceof ErrorDTO) {
        ...
    }
}

Hope it's useful!

I tried Alfredo's solution but I got an Exception because of Object.class:

Method threw 'org.springframework.web.client.HttpClientErrorException' exception.

If you use a different class, it would be casted and you wouldn't be able to use instance of.

Using following code solved my problem:

String xml = restTemplate.getForObject(url, String.class, uriVariables);
JAXBContext jaxbContext = JAXBContext.newInstance();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringSource xmlStr = new StringSource(xml);
Object o = jaxbUnmarshaller.unmarshal((Source) xmlStr);
if (o instanceof VonAZRAZRBestaetigungMeldung090098) {
    // ...
}
Related