Skip to main content

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
  • making connections
  • caching
  • retrying failed requests
  • threading
  • response parsing
  • error handling, and more. 
Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes - 
  • Model class to map the JSON data
  • Interfaces which defines the possible HTTP operations
  • Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation.
Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object.
So, without any further delays, let's get our hands dirty with some code.

Project setup 

To create a project in Eclipse IDE, follow below steps - 
  1. Navigate to File ⇨ New ⇨ Project ⇨ Maven ⇨ Maven Project ⇨ Next
  2. Select archetype for the maven project and then Next
  3. Add project details and click on Finish. 
  4. Now add following dependencies in the pom.xml file.
  

Sample XML

A sample XML RSS feed response looks likes

Code in Action

First, we need to create the model classes - one for each article and other for the feed. Let's first create a class for the article.

Let us understand the code now. We have used different annotations in this class

  1. @Root - This indicates that the class is serialized/deserialized. It represents the element in the XML. The name property signifies the element name. If it is not defined, then the class name is used as the element name. With strict set to false, strict parsing is disabled. This tells the parser to not fail and throw an exception if an XML element or attribute is found for which no mapping is provided.
  2. @Element - It represents an XML element. If no name is specified, the field name will be used.
Now, let us create the model class for the RSS feed.
Some other annotations used are
  1. @ElementList - This indicates the collection is being used. With inline set to true, it is determined that the elements of the Collection are inlined. That means, that they have no enclosing element and are listed one after another within the XML response.
  2. @Path - We can provide a path to an XML element inside the XML tree.
Now, after creating the models, let's expose the API via an interface.

To call the API, let'ss create a controller that creates a Retrofit client and handles the result.
Now, to run this application below is the main class

Result

After running the application, the output will be as below

Channel Title: Times of India
----------------------------------------------

Title: RS Dy chair poll: BJD, TRS boost to NDA; oppn questions Cong strategy
Link: https://timesofindia.indiatimes.com/india/rs-dy-chairperson-election-bjd-trs-boost-to-nda-oppn-questions-congress-strategy/articleshow/65342145.cms

Title: Kerala rains live: 26 dead, CM says situation grim
Link: https://timesofindia.indiatimes.com/city/kochi/heavy-rains-hit-life-in-kerala/articleshow/65335799.cms

Title: AAP won't join oppn alliance for LS polls: Kejriwal
Link: https://timesofindia.indiatimes.com/india/aap-will-not-join-opposition-alliance-for-2019-lok-sabha-polls-kejriwal/articleshow/65344573.cms

Title: Samsung launches Galaxy Note 9: Specs and more
Link: https://www.gadgetsnow.com/mobiles/samsung-galaxy-note-9-with-improved-s-pen-launched-price-specifications-and-availability/articleshow/65342896.cms

Title: US-China trade war may bring cheaper oil to India
Link: https://timesofindia.indiatimes.com/business/india-business/how-us-china-trade-war-may-bring-cheaper-oil-to-indian-shores/articleshow/65333316.cms

Conclusion

Thus, we have seen that it is very easy to parse the XML response using the Retrofit library. A lot of boilerplate code has been eliminated. This increases the faster time to market and maintenance of code becomes very easy. You can find the complete code on GitHub
That's it for today. I hope you enjoyed this post. Happy Coding!! 😊

Comments

Popular posts from this blog

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Threads in Java - Basics (Part 1)

Hello everyone, today we are going to discuss one of the most important concepts in Java - Multithreading.
In the first part of this multi-part blog series, we will be discussing the basics of threads, how can we create them? which is the best approach? and many other questions like these. So without further ado, let's get started.
What are threads? Let's say you are Batman (pretty cool, eh? 😊) and your arch-enemy, the master alchemist Ra's al Ghul has brewed a dangerous potion from the Lazarus Pit. To avenge his earlier defeats by the hands of The Dark Knight, he has spread the potions all over the Gotham city.  Now, the only way to save citizens of Gotham is to find the cure of the potion (hidden in the city somewhere) and find Ra's as well before he can devise a new plan to destroy the city.  Batman calls Nightwing (the original Robin) and asks his help in finding Ra's. Batman decides to find the cure of the deadly potion. In the end, both Batman and Robin wer…