Retrofit 2 — Custom DeSerializer for Unwrapping Properties

One of the interesting things about using libraries to perform part of the work on a feature is automating things that are really boring and hard work as is the case of dealing with Http + Restful + Error Handler + Parse + a lot of stuffs. In Android we almost always have to deal with the integration of some API, and Retrofit has become the solution most used for this purpose.

Not always Restfull API are developed following best practices, or even are legacy APIs, and at some point we come across this scenario.
Recently I was working with an API where one of the requisitions was breaking the App, after some time debugging I found the cause, I will represent a response model to illustrate the case.

The Json issue

As you can see, the task property in json can be an object or an array, to solve this problem, we will create a custom deserializer for this property and place the @Deserializer annotation in our model class. So when Jackson finds this note, he’ll delegate our class to deserialize that property.

Classes Model

Let’s do a Task wrapper class for the Task class, because we need this class to be used in our Deserializer.

Here, we will create a custom StdDeserializer class and make the parser for the task property in json, we just need to verify that the {“tasks”: “”} property is an array or object and convert json to java.

Now, we need to register the custom Deserializer class in SimpleModule so that Jackson can use it.

I hope it be helpful to another developers, and feel free to leave a comment with suggestions.