Mobimeo Technology
Published in

Mobimeo Technology

How to create a generic Moshi JsonAdapter that returns default value on malformed objects.

Photo by Tim Arbaevon Canva

Introduction

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

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.

DefaultOnMalformedDataAdapter.kt

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store