Migrate from GSON to Moshi in Android
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.
param3 is newly added to the upcoming release. So the server in production’s response does not contain
param3 and accessing
param3Int caused a
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
JsonDeserializerto 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.
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.
@Json and add
@JsonClass. Then, it is done.
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.