This tutorial is about the basics of Retrofit library and solving the problem of extracting nested objects from the API calls as JavaBeans .
Retrofit is a great library from Square that let’s you structure your api calls as declarative, type-safe callable interfaces.
Even though their docs are great and more than enough to start using the library, solving more complicated problems requires more digging. It took me some time and searching through stackoverflow to figure out a way to extract nested objects from API responses so I hope this article will save you some of that time.
Dependencies
This is the list of the dependencies needed for this tutorial:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'implementation 'com.squareup.retrofit2:converter-gson:2.4.0'implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'implementation 'com.squareup.okhttp3:okhttp:3.12.0'
API call structure
In this tutorial I’m going to make calls to my back-end API and extract user data.
This is what my user data call result looks like:
|
|
The part that we’re trying to retrieve from the result is nested under result json.
This is what my JavaBean looks like. As you can see the structure and the variable names must reflect result json.
|
|
Implementation
When starting a new project with Retrofit I like to split the logic in three interdependent parts:
- Retrofit client builder — Responsible for creating new instances of the Retrofit client
- Custom Deserializer — Extracts nested objects from the response
- Call interfaces — Interfaces to defines API calls
- Client Builder
This what RetrofitClientBuilder looks like:
|
|
BASE_URL– Base url for all the endpoint callsgetRetrofit()– Initiates the Retrofit client instance. It usesOkHttplibrary to make actual requests. When buildingOkHttpinstance we set a timeout for 10 seconds, you can change that value of course. To convert server response fromjsonto JavaBean we use an instance ofGsonwhich is returned fromgetConverter()methodgetConverter()– Returns an new instance of theGsonclass with type adapters we register to use our JavaBeans. As you can see we registerUserJavaBean we defined, but you can also register primitives likeString.
- Deserializer
Next we define MyDeserializer class we used in getConverter method. It’s responsible for extracting the nested result object from our json response.
|
|
MyDeserializer implements JsonDeserializer<T> interface where T stands for a generic type. Using this generic implementation we’re able to reuse MyDeserializer for multiple different JavaBeans. This interface has only one deserialize method that we need to override. je variable is JsonElement created from our server response json, so it has the same structure. We extract the nested result object from je and create an instance of our JavaBean object using Gson and return it.
- Callable Interfaces
In callable interfaces we declaratively define the structure of our REST calls. Here’s what they look like:
|
|
@POST defines the request method (which is post, duh) and the url address of the endpoint which will be combined with BASE_URL we defined earlier to build full http path to your endpoint. @Body defines the body of the request. It doesn’t have to be HashMap you can use other objects defined in
Retrofit docs
.
Usage
Here’s the code for making a request on a separate thread using Thread objects. I don’t advice using this method, I used it to keep this tutorial short. I advice using AsyncTask or
RxJava
library for handling asynchronous tasks in Android:
|
|
- We create an instance of our callable interface using
ApiManager.getRetrofit()we defined earlier - We define parameters for our post request using
paramshashmap - Finally we get an instance of the
Callobject usinggetUserInfomethod we defined in our interface and callexecuteandbodymethods to execute and get the body of the response. - If everything is working correctly
bodymethod should returnUserpopulated with the fields from theresultnested object.
And that’s the end of this tutorial, hopefully you were able to follow through and get your Retrofit setup working. Retrofit is a great library and a must have for any Android developer who wishes to keep his/her code clean and maintainable.
If you’d like to get more web development, React and TypeScript tips consider
following me on Twitter,
where I share things as I learn them.
Happy coding!