Member preview

Migrate from GSON to Moshi in Android

Android Image from foter.com

I received a call from client this morning. They accidentally put the UAT version Android apk in production. This caused multiple devices stop functioning with the not updated server.

Even though it is client’s fault, the application should not crash. I decided to investigate the cause.

Response model from server

param3 is newly added to the upcoming release. So the server in production’s response does not contain param3 and accessing param3Int caused a NullPointerException.

However, I am using Retrofit2 to handle the REST request which has error handler to handle the error during retrieving JSON. It turns out it is not called because GSON decides to set the field to null instead of throwing exception for a missing field.

To solve this problem, we have two solutions:

  • Write an Annotation and JsonDeserializer to check for missing field.
  • Make all the fields in the data class nullable.

The first one introduces a lot of unnecessary code to code base. The second default the purpose of using Kotlin to write null safe code instead of checking null everywhere.

Then, I find out Moshi.

What is Moshi?

Moshi is a JSON serialization library written by square who creates retrofit and okhttp.

Installation

Add the dependencies to your .gradle

We added three library. The first one moshi is the core library. The second one moshi-kotlin is the integration for Kotlin. The last one moshi-kotlin-codegen all us to generate code in compile time instead of using runtime reflection.

Refactor

We replace GsonConverterFactory with MoshiConverterFactory, @SerializedName with @Json and add @JsonClass. Then, it is done.

That’s it?

Yes, that’s it. Now Moshi can parse JSON based on Kotlin declaration to determine a field can be nullable or not.

While GSON is a more well-known library, the releases seems to be stale. Only minor changes is released over the years and we see there is no plan to integrate with Kotlin.

If you are writing Android app with Kotlin (You absolute should use Kotlin over Java in Android), you should use Moshi instead of GSON for JSON serialization library.