Receiving XML via REST

Well every time I think about implementing/using REST application, I am always having this stereotypical picture in mind: REST + JSON. However, REST is just Representation State Transfer paradigm and means  only stateless, client-server, cacheable communication with uniform interface and the format the RESTful service will provide is an implementation detail. Interestingly enough there is even an opinion that JSON is not RESTful at all, that you can check out here, but which doesn’t make much sense to me. I am more of the opinion that JSON is much more easy to use than XML, some arguments regarding this described on W3Schools.com.

In any case recently I had a problem to get data from a 3rd party web-site via provided REST API, because the format it serves data is XML. I was using RestTemplate provided by Spring to get the data. So if in case of response coming in JSON format, the code would be basically one line:

MyObject objectResponse = restTemplate.getForObject("http://someurl", MyObject.class);

where MyObject keeps structure accordingly and has few annotations. This can be achieved by simply having Jackson in your class path. RestTemplate is smart enough to figure message converter out (you can find out more in official example from Spring). I was searching for a short elegant solution to parse my XML response same way.

However marshalling XML response is not possible out-of-the-box with Spring, we need third-party library to achieve that. Spring implementation for Android uses  Simple internally to provide desired behaviour. The most short and working solution I found so far was using  JAXB (Java Architecture for XML Binding)

final StreamSource source = restTemplate.getForObject(url, StreamSource.class);

try {
    JAXBContext jaxbContext = JAXBContext.newInstance(Tixik.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    Tixik restHotel = (Tixik) jaxbUnmarshaller.unmarshal(source);

} catch (JAXBException e) {
    LOG.error("Failed to parse response from {}", url, e);
}

Where my Tixik.class contains proper POJO mapping structure and annotations @XmlRootElement, @XmlElement to support correct parsing.

This worked nicely for me, maybe it helps you one day  or you find out better solution and share it with me 🙂

And well… I still prefer JSON, because my POJO matching XML structure looks really ugly!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s