How to create a generic Moshi JsonAdapter that returns default value on malformed objects.
On one of our projects, I use Moshi for JSON parsing with Retrofit. Moshi is a modern JSON library for Java and Kotlin. It makes it easy to parse JSON into Java and Kotlin classes.
The real-life problem
Recently I faced an issue where one of the API calls in the app has no API versioning. We get public transport ticketing data from a 3rd party partner API, keeping in mind the API response needs to be stored as BLOB (VmState) because we send the same unmodified response back to them when the user eventually decides to buy the ticket.
So when our 3rd party backend changes their API call response, this affects older versions of our App.
Sometimes they send some malformed object inside the BLOB, while some of the other JSON data can still be used. Instead of throwing a JsonDataException, I need to provide a default value for the malformed JSON data.
The solution would be to create a custom JSON adapter that has a default value constructor parameter for the malformed JSON data and that inherits the Moshi JsonAdapter class.
I added a static factory method so that the DefaultOnMalformedDataAdapter could be used for the T type of class as a generic.
When a class extends a JsonAdapter class, the class could override two methods related to JSON parsing: fromJson, and toJson. In the toJson method when the JSON parsing throws a JsonDataException it returns the defaultValue that we provided via the contractor before.
And for the specific example for TicketingPaylod class, we build the Moshi adapter like this.
Thanks for reading! Hope you found this useful.
If you like what you read, clap 👏 it below.