How to use custom gson converter to parse dynamically changing json with Retrofit 2, Android

We often come across situations where our json response contains attributes that switches its type dynamically. For example , if a particular key returns JSONObjectusually, but in some errror conditions it returns just an error message which is a String. In such cases, if we have configured our network callbacks to return a JSONObject then when a String is returned for error case, the network method callbacks may not be able to handle the response. In such cases we will have to perform dynamic json parsing. For such cases, you may use JsonDeserializer to intercept the response and convert it to appropriate type(using gson) even before it reaches the network method callbacks(onResponse,onFailure in case of retrofit).

Consider the following json structure in which the key responseMessage dynamically changes between a String and a JSONObject

Here we have subclassed ResponseMessage, ResponseString from ResponseWrapper. The reason for this approach is that deserialize() method defined in UserResponseDeserializer have a return type of ResponseWrapper, so either of the subclassed classes can be returned from deserialize() depending on the response is an object/string

The deserialize() method is an overridden method that provides us with the json to be parsed. Here we can check the type of the json(json object/string) using instanceof method and decide whether to return ResponseMessage.class/ResponseString.class

Now pass the above UserResponseDeserializer to our GsonConverterFactory to complete the implementation of our custom gson converter as shown below

Thats it! you can now parse a json key which dynamically switches as a json object/string. Similar procedures can be followed for json arrays as well(just check instanceof JsonArray)You may also check this example which provides free source code download