I have been creating Android applications for about 10 ten years or so now. I have blindly utilised Gson for serialisation and deserialization in every single small or large Android app I have produced. Gson appeared to be perfect and almost know what I was thinking. But it’s now time to say goodbye and move to Moshi.
So let’s check how Gson is doing right now before we discuss why Moshi is a superior alternative and how we should switch to using it
- Gson was a library created by Google using java to serialize and deserialize an object.
- Gson has a huge number of methods making you hit your dex limit fast.
- Gson uses reflection to serialize and deserialize objects.
- There is no support for default values when using Gson.
So if not for Gson, then who?
Moshi is a modern JSON library written in Kotlin and Java as per their repo. But what makes them modern? Let’s find out.
- Moshi is fast!
- Square’s Moshi can be seen as GSON’s replacement because it has a cleaner and simpler API and an architecture that makes greater use of the Okio library for improved speed. Because it includes Kotlin-aware extensions, it is also the most Kotlin-friendly library you can use to parse JSON files.
- Moshi respects default values.
- Moshi would assign the provided default values when reading JSON that was missing a field, preventing unintentional null pointer errors at runtime.
- Code Generation.
- Moshi has a feature that uses an annotation processor to generate code at build time and does not rely on reflection.
Okay but I have a legacy project with Gson used all over the place. What do I do?
Migrating to Moshi from Gson is very easy.
- Integrate Moshi from the read me page here.
- Replace SerializedName with Json so this
@SerializedName(“username”) val userName: String?will change to
@Json(“username”) val userName: String?if you are using Moshi
- Annotate Data classes with
@JsonClass(generateAdapter = true)to allow code generation.
- Replace your from and to Json methods to use Moshi so
gson.fromJson(jsonString, class)will change to
- Replace the retrofit converter factory so
GsonConverterFactory.create()will be replaced with
MoshiConverterFactory.create()and retrofit should be able to convert everything properly
And that’s pretty much it. You have successfully replaced Gson with Moshi.
Thanks for reading, if you have my articles feel free to subscribe to my newsletter or share the article.